Thursday, 25 May 2017

I'm confused with the module in node.js

there are three modules: a.js,b.js,c.js, a.js is to export a database connection, and b.js,c.js is to import the connection just like in two different http routes, so the connection module(a.js) will be imported two times, does it mean the driver will connect to the database two times?

I have tried like this: test.js

let a = 20;
let b = 30;
console.log('I am test');
let obj = {
    a,
    b
}
module.exports = obj;

en.js

let obj = require('./test');

console.log('I am en.js')

module.exports = obj;

hi.js

let obj = require('./test');
let obj2 = require('./en');

console.log(obj2)

run hi.js and the result:

I am test
I am en
{a:20,b:30}

en.js and the hi.js both import the test.js, from the results it seems that the test.js only runs once, so why? Hope your help.



via laoqiren

No comments:

Post a Comment