0

Let say that I have javascript file like following, which include global variable and global function. How could this best be included in node js with express?

var language = {
    'English': 'English'
}

var a = 'string';

function start() {
    return 'start';
}

var b = function() {
    return 'start';
}

1 Answer 1

5

node.js uses the module system for including files. While you can actually conciously assign global variables in node.js, that is not recommended. You could instead, wrap your functions in a module and export the functions you intend to be public. Other JS files that wish to use these functions would then require() in your module and reference the functions from the returned module handle. This is the recommended way of sharing code between files in node.js.

It is unclear what your module is supposed to do, but you could export two functions like this:

// module shared.js
function start() {
    return 'start';
}

var b = function() {
    return 'start';
}

module.exports = {
    start: start,
    b: b
};

Then, another module could use this like this:

// module main.js
var shared = require('./shared.js');

console.log(shared.b());
console.log(shared.start());
Sign up to request clarification or add additional context in comments.

2 Comments

i have came across the usage of app.locals for express. is there any advantage of using app.locals comparing to this?
@desmondlee - It depends upon what you're sharing. In Express app.locals is common place to put application specific configuration information. Since it requires Express and typically many modules in your application are not Express-specific, I would not use it for modules that have generic usefulness outside of Express. Remember, for maximum sharability and code reuse, modules should be as independent as possible. Only make something depend upon Express if it can only be used with Express. Also, to use app.locals, you will have to first share the app object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.