How can I assign variables to modules in RequireJS?
In other words, what is the RequireJS equivalent of this:
var fs = require('fs');
var child_process = require('child_process');
I want to save these modules in their respective variables so I can call their functions and deal with them later.
Edit:
I tried using what Marco suggested and this is the error I get:
Failed to load resource: the server responded with a status of 404 (Not Found) localhost/fs.js
Uncaught Error: Script error for: fs requirejs.org/docs/errors.html#scripterror
Then I placed the fs.js file right in the project directory and now the error says:
Uncaught Error: Module name "fs" has not been loaded yet for context: _. Use require([]) requirejs.org/docs/errors.html#notloaded
Uncaught TypeError: Cannot read property 'writeFile' of undefined
Please suggest some workaround to this.
The equivalent in requirejs of what you wrote would be
require(['fs','child_process'], function (fs, child_process) {
//fs and child_process are now loaded
});
If you need to change the name of the import just change the name of the argument of the function.
Also remember that the load order of fs and child_process is not guaranteed. If you need to load fs before child_process, you need to make two distinct calls o require()
When you use above call, RequireJS will look for two files, fs.js and child_process.js from the same host where the script comes from. The path is relative to the so called baseUrl. From the documentation:
If there is no explicit config and data-main is not used,
then the default baseUrl is the directory that contains
the HTML page running RequireJS.
For example, if you load RequireJS from http://localhost/index.html, it will look for http://localhost/fs.js and http://localhost/child_process.js. If for some reasons the file is located elsewhere, (e.g. it's an external library), you can specify a different path.
Keep in mind that you can't just load Node modules from the browser (as it seems you're trying to do), even if you're using Node on the server side. Some of them don't even make sense in a browser (child_process for example), others may be available as standalone modules for npm or bower, but I have no experience with that.
If instead you're trying to use RequireJS server-side as a module system for Node, you can check out the relevant page.