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


当前回答

Node基于commonjs模块和最近的esm模块工作。基本上,你应该在独立的.js文件中创建模块,并使用导入/导出(module. js)。导出和要求)。

基于作用域,浏览器上的Javascript工作方式不同。有全局作用域,通过clojures(其他函数中的函数)可以获得私有作用域。

因此,在node中,导出将在其他模块中使用的函数和对象。

其他回答

比如你有一个abc.txt文件或者更多?

创建两个文件:fileread.js和fetchingfile.js,然后在fileread.js中编写以下代码:

function fileread(filename) {
    var contents= fs.readFileSync(filename);
        return contents;
    }

    var fs = require("fs");  // file system

    //var data = fileread("abc.txt");
    module.exports.fileread = fileread;
    //data.say();
    //console.log(data.toString());
}

在fetchingfile.js中编写以下代码:

function myerror(){
    console.log("Hey need some help");
    console.log("type file=abc.txt");
}

var ags = require("minimist")(process.argv.slice(2), { string: "file" });
if(ags.help || !ags.file) {
    myerror();
    process.exit(1);
}
var hello = require("./fileread.js");
var data = hello.fileread(ags.file);  // importing module here 
console.log(data.toString());

现在,在终端中: $ node fetchingfile.js——file=abc.txt

你将文件名作为参数传递,并且在readfile.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');

当然,这很有帮助。

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

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

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

我只是想补充一点,如果你只需要从你的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文件夹加载。