简体   繁体   中英

Can you call functions from an imported module without calling the module in node.js?

Kind of a dumb question, just wanted to try out if you could just avoid the name of the required module.

For example:

const MATH = require('./maths.js');
HTTP.createServer(function (request, response) {
    response.write("Add 1 and 5: " + MATH.add(1, 5));
}).listen(8080);

// Add in the maths module
// function add(a, b) {
//     return a + b;
// }

Would I be able to somewhat do the following?

response.write("Add 1 and 5: " + add(1,5));

Yes you can by using ES6 destructuring. How? Like this:

const { add } = require('./maths.js');

HTTP.createServer(function (request, response) {
    response.write("Add 1 and 5: " + add(1, 5));
}).listen(8080);

// Add in the maths module
// function add(a, b) {
//     return a + b;
// }

Should work in Node 10+ (even earlier)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM