desmondlee
desmondlee

Reputation: 1703

global variable and function in node js

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';
}

Upvotes: 0

Views: 7446

Answers (1)

jfriend00
jfriend00

Reputation: 708026

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());

Upvotes: 5

Related Questions