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


当前回答

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

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

其他回答

要在Unix环境中交互式地测试模块./test.js,可以使用这样的代码:

    >> node -e "eval(''+require('fs').readFileSync('./test.js'))" -i
    ...

你可以要求任何js文件,你只需要声明你想公开什么。

// tools.js
// ========
module.exports = {
  foo: function () {
    // whatever
  },
  bar: function () {
    // whatever
  }
};

var zemba = function () {
}

在你的应用文件中:

// app.js
// ======
var tools = require('./tools');
console.log(typeof tools.foo); // => 'function'
console.log(typeof tools.bar); // => 'function'
console.log(typeof tools.zemba); // => undefined

在我看来,另一种方法是在调用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(),它将是相同的。希望能有所帮助。

要把“工具”变成一个模块,我一点也不觉得困难。尽管有其他的答案,我仍然建议使用module.exports:

//util.js
module.exports = {
   myFunction: function () {
   // your logic in here
   let message = "I am message from myFunction";
   return message; 
  }
}

现在我们需要将这个exports分配到全局作用域(在你的应用程序|index|server.js中)

var util = require('./util');

现在你可以引用和调用函数为:

//util.myFunction();
console.log(util.myFunction()); // prints in console :I am message from myFunction 

我也在寻找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');

当然,这很有帮助。