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


当前回答

下面是一个简单明了的解释:

Server.js内容:

// Include the public functions from 'helpers.js'
var helpers = require('./helpers');

// Let's assume this is the data which comes from the database or somewhere else
var databaseName = 'Walter';
var databaseSurname = 'Heisenberg';

// Use the function from 'helpers.js' in the main file, which is server.js
var fullname = helpers.concatenateNames(databaseName, databaseSurname);

Helpers.js内容:

// 'module.exports' is a node.JS specific feature, it does not work with regular JavaScript
module.exports = 
{
  // This is the function which will be called in the main file, which is server.js
  // The parameters 'name' and 'surname' will be provided inside the function
  // when the function is called in the main file.
  // Example: concatenameNames('John,'Doe');
  concatenateNames: function (name, surname) 
  {
     var wholeName = name + " " + surname;

     return wholeName;
  },

  sampleFunctionTwo: function () 
  {

  }
};

// Private variables and functions which will not be accessible outside this file
var privateFunction = function () 
{
};

其他回答

我也在寻找一个选项,包括代码而不编写模块,respp。为Node.js服务使用来自不同项目的相同测试独立源- jmparattes回答为我做了这件事。

这样做的好处是,您不会污染名称空间,我不会遇到“使用严格”的问题;而且效果很好。

以下是完整的样本:

加载脚本- /lib/foo.js

"use strict";

(function(){

    var Foo = function(e){
        this.foo = e;
    }

    Foo.prototype.x = 1;

    return Foo;

}())

SampleModule - index.js

"use strict";

const fs = require('fs');
const path = require('path');

var SampleModule = module.exports = {

    instAFoo: function(){
        var Foo = eval.apply(
            this, [fs.readFileSync(path.join(__dirname, '/lib/foo.js')).toString()]
        );
        var instance = new Foo('bar');
        console.log(instance.foo); // 'bar'
        console.log(instance.x); // '1'
    }

}

希望这对你有所帮助。

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.

希望有帮助。

假设我们想调用函数ping()和add(30,20),这是在lib.js文件 从main.js

main.js

lib = require("./lib.js")

output = lib.ping();
console.log(output);

//Passing Parameters
console.log("Sum of A and B = " + lib.add(20,30))

lib.js

this.ping=function ()
{
    return  "Ping Success"
}
//Functions with parameters
this.add=function(a,b)
    {
        return a+b
    }

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

在我看来,最干净的方法是在tools.js中:

function A(){
.
.
.
}

function B(){
.
.
.
}

module.exports = {
A,
B
}

然后,在app.js中,只需要如下所示的tools.js: const tools = require("tools");