是否可以将一种方法转换为 nodejs 和 express 中的另一个文件? [英] Is it possible to one method into another file in nodejs and express?

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

问题描述

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

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 函数,按照我说的方式导入它,你可以在任何你想要的地方使用它(在需要之后).

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 文档,描述一下精心制作.

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

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