Is it possible to one method into another file in nodejs and express?

折月煮酒 提交于 2019-12-24 10:51:00

问题


how can I use one method into entire project is it possible? If it's possible please help me with detail.

Thanks Advance


回答1:


As an example its your log.js file.You can use module.exports to export a function like this

module.exports.log = function (msg) { 
    console.log(msg);
};

Now if you want to import it in ,suppose app.js file.Just do something like this.

var msg = require('./Log.js');// the path is important here 

msg.log('Hello World');

In above example you are exporting log function ,import it with the way I told and you can use it anywhere you want (after requiring).

Better have a look at the docs too.

You can also use ES6 export and import,something like below

export function log(){ } // exports named function log
import { log } from '..filepath/filename'

MDN docs ,describe it elaborately.



来源:https://stackoverflow.com/questions/56928759/is-it-possible-to-one-method-into-another-file-in-nodejs-and-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!