Is there a way in Node.js to define a "Standard Library", which is automatically executed at the start of every Node.js App?
For example:
//stdlibrary.js
function sayHello(){
console.log("Hello World!");
}
//app.js
sayHello(); //without including the stdlibrary.js!
Hope my question is clear.
Thanks for your help!
Update
I´m looking for something like the auto_prepend_file
in PHP. Hope there is something similar to this.
Is there a way in Node.js to define a "Standard Library", which is automatically executed at the start of every Node.js App?
For example:
//stdlibrary.js
function sayHello(){
console.log("Hello World!");
}
//app.js
sayHello(); //without including the stdlibrary.js!
Hope my question is clear.
Thanks for your help!
Update
I´m looking for something like the auto_prepend_file
in PHP. Hope there is something similar to this.
4 Answers
Reset to default 4Yes, this is simple to do. Just edit the src/node file to include an option for an autorequire file, and then modify the node::Load code to handle the option. You probably also need to change the javascript in src/node.js.
Rebuild, test and you are done.
Or you could probably just hack this into src/node.js by having it eval a string that requires your library and then evals the actual script file mentioned on the mand line.
There's no such thing in node.js, this kind of magic is not transparent and because of this reason gladly avoided by the most software products.
I suggest to create a file mon.js that you include in each other file:
var mon = require("./mon")
You can then access constants and functions that are exported in mon.js as follows:
mon.MY_CONST
mon.my_fun()
mon.js would be implemented like:
exports.MY_CONST = 123
exports.my_fun = function() {
...
}
Another option is to 'pollute' the global namespace (but it is not remended at all). You could define an object containing your functions in a file (let's call it global.js):
global.js:
global.customNs = {};
global.customNs.helloparam = function(param) {
console.log('Hello ' + param);
};
In your mainfile (your server or whatever kind of app you are developing), you require that file once:
server.js
require('./global');
After requiring it, you can access your global.customNs.helloparam function in all following requires (basically everywhere).
Another option is to define a global object using CommonJS module notation:
global.js
exports.customNs = {
global.customNs.helloparam = function(param) {
console.log('Hello ' + param);
};
}
server.js
globalObject = require('./global').customNs;
Then access it using globalObject.helloparam('test') anywhere in your require'd code.
Note: i don't use either of those in production code, just threw this examples together using some testing code. Can't guarantee they work under any circumstances