是否可以将一种方法放入nodejs中的另一个文件并进行表达? [英] Is it possible to one method into another file in nodejs and express?

查看:163
本文介绍了是否可以将一种方法放入nodejs中的另一个文件并进行表达?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在整个项目中使用一种方法? 如果可能,请详细帮助我.

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

感谢进阶

推荐答案

例如,它是您的log.js文件.您可以使用module.exports导出类似这样的函数

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

现在,如果要将其导入到app.js文件中,只需执行以下操作即可.

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

在上面的示例中,您正在导出log function,按照我告诉的方式将其导入,并且可以在需要的任何地方使用它(在需要之后).

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).

最好也看看文档.

您还可以使用ES6 exportimport,如下所示

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

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

MDN文档,对其进行描述精心制作.

MDN docs ,describe it elaborately.

这篇关于是否可以将一种方法放入nodejs中的另一个文件并进行表达?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆