假设我有一个叫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文件的基本导入。


当前回答

我也在寻找NodeJS的“包含”函数,我检查了Udo G提出的解决方案-请参阅消息https://stackoverflow.com/a/8744519/2979590。他的代码不能与我所包含的JS文件一起工作。 最后我是这样解决问题的:

var fs = require("fs");

function read(f) {
  return fs.readFileSync(f).toString();
}
function include(f) {
  eval.apply(global, [read(f)]);
}

include('somefile_with_some_declarations.js');

当然,这很有帮助。

其他回答

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.

希望有帮助。

您可以将函数放在全局变量中,但更好的做法是将工具脚本转换为模块。这并不难——只需将您的公共API附加到exports对象。看一看理解Node.js的exports模块,了解更多细节。

Node.js中的vm模块提供了在当前上下文中(包括全局对象)执行JavaScript代码的能力。看到http://nodejs.org/docs/latest/api/vm.html vm_vm_runinthiscontext_code_filename

请注意,到今天为止,vm模块中有一个错误,它阻止runInThisContext在从新上下文调用时执行正确的操作。只有当你的主程序在一个新的上下文中执行代码,然后该代码调用runInThisContext时,这才重要。参见https://github.com/joyent/node/issues/898

遗憾的是,Fernando建议的with(global)方法不适用于“function foo(){}”这样的命名函数。

简而言之,这是一个适用于我的include()函数:

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

创建两个js文件

// File cal.js
module.exports = {
    sum: function(a,b) {
        return a+b
    },
    multiply: function(a,b) {
        return a*b
    }
};

js主文件

// File app.js
var tools = require("./cal.js");
var value = tools.sum(10,20);
console.log("Value: "+value);

控制台输出

Value: 30

在我看来,另一种方法是在调用require()函数时执行lib文件中的所有内容,使用(function(/* things here */){})();这样做将使所有这些函数都具有全局作用域,就像eval()解决方案一样

src / lib.js

(function () {
    funcOne = function() {
            console.log('mlt funcOne here');
    }

    funcThree = function(firstName) {
            console.log(firstName, 'calls funcThree here');
    }

    name = "Mulatinho";
    myobject = {
            title: 'Node.JS is cool',
            funcFour: function() {
                    return console.log('internal funcFour() called here');
            }
    }
})();

然后在你的主代码中,你可以像这样调用函数的名字:

main.js

require('./src/lib')
funcOne();
funcThree('Alex');
console.log(name);
console.log(myobject);
console.log(myobject.funcFour());

会得到这样的输出

bash-3.2$ node -v
v7.2.1
bash-3.2$ node main.js 
mlt funcOne here
Alex calls funcThree here
Mulatinho
{ title: 'Node.JS is cool', funcFour: [Function: funcFour] }
internal funcFour() called here
undefined

当你调用我的object.funcFour()时,请注意未定义,如果你加载eval(),它将是相同的。希望能有所帮助。