假设我有一个叫app。js的文件。很简单:

var express = require('express');
var app = express.createServer();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/', function(req, res){
  res.render('index', {locals: {
    title: 'NowJS + Express Example'
  }});
});

app.listen(8080);

如果我在“tools.js”中有一个函数。我如何将它们导入到apps.js中使用?

还是……我应该把“工具”变成一个模块,然后需要它吗?<<似乎很难,我宁愿做tools.js文件的基本导入。


当前回答

它与我的工作如下....

Lib1.js

//Any other private code here 

// Code you want to export
exports.function1 = function(params) {.......};
exports.function2 = function(params) {.......};

// Again any private code

现在在Main.js文件中,你需要包含Lib1.js

var mylib = requires('lib1.js');
mylib.function1(params);
mylib.function2(params);

请记住将Lib1.js放在node_modules文件夹中。

其他回答

使用node.js和express.js框架时的另一种方法

var f1 = function(){
   console.log("f1");
}
var f2 = function(){
   console.log("f2");
}

module.exports = {
   f1 : f1,
   f2 : f2
}

将其存储在一个名为s的js文件中,并保存在statics文件夹中

现在使用这个函数

var s = require('../statics/s');
s.f1();
s.f2();

我只是想补充一点,如果你只需要从你的tools.js中导入某些函数,那么你可以使用解构赋值,这在node.js版本6.4中得到了支持-参见node.green。


例子: (两个文件在同一个文件夹中)

tools.js

module.exports = {
    sum: function(a,b) {
        return a + b;
    },
    isEven: function(a) {
        return a % 2 == 0;
    }
};

main.js

const { isEven } = require('./tools.js');

console.log(isEven(10));

输出:真正的


这也避免了你将这些函数赋值为另一个对象的属性,就像下面(常见)赋值的情况一样:

Const tools = require('./tools.js');

你需要调用tools.isEven(10)。


注意:

不要忘记在文件名前面加上正确的路径——即使两个文件在同一个文件夹中,也需要加上。/前缀

来自Node.js文档:

没有前导'/','。/',或'../'表示一个文件,模块 必须是核心模块或从node_modules文件夹加载。

Udo G.说:

eval()不能在函数内部使用,必须在函数内部调用 全局作用域,否则没有函数或变量 可访问(即不能创建include()实用函数或 差不多吧)。

他是对的,但是有一种方法可以通过函数来影响全局作用域。改进他的例子:

function include(file_) {
    with (global) {
        eval(fs.readFileSync(file_) + '');
    };
};

include('somefile_with_some_declarations.js');

// the declarations are now accessible here.

希望有帮助。

包含文件并在给定的(非全局)上下文中运行它

fileToInclude.js

define({
    "data": "XYZ"
});

main.js

var fs = require("fs");
var vm = require("vm");

function include(path, context) {
    var code = fs.readFileSync(path, 'utf-8');
    vm.runInContext(code, vm.createContext(context));
}


// Include file

var customContext = {
    "define": function (data) {
        console.log(data);
    }
};
include('./fileToInclude.js', customContext);

使用ESM模块系统:

a.js:

export default function foo() {};

export function bar() {};

研究:

import foo, {bar} from './a.js';