Van Coding
Van Coding

Reputation: 24524

Node.js - Standard Library

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.

Upvotes: 2

Views: 2216

Answers (4)

schaermu
schaermu

Reputation: 13460

Another option is to 'pollute' the global namespace (but it is not recommended 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

Upvotes: 0

Michael Dillon
Michael Dillon

Reputation: 32392

Yes, this is simple to do. Just edit the src/node.cc 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 command line.

Upvotes: 4

Tobias P.
Tobias P.

Reputation: 4665

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.

Upvotes: 3

alienhard
alienhard

Reputation: 14672

I suggest to create a file common.js that you include in each other file:

var common = require("./common")

You can then access constants and functions that are exported in common.js as follows:

common.MY_CONST
common.my_fun()

common.js would be implemented like:

exports.MY_CONST = 123
exports.my_fun = function() {
    ...
}

Upvotes: 2

Related Questions