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


当前回答

您不需要新的函数或新的模块。 如果不想使用命名空间,只需执行正在调用的模块。

在tools.js

module.exports = function() { 
    this.sum = function(a,b) { return a+b };
    this.multiply = function(a,b) { return a*b };
    //etc
}

在app.js

或任何其他。js,如myController.js:

而不是

Var tools = require('tools.js'),这迫使我们使用命名空间并调用工具,如tools.sum(1,2);

我们可以简单地调用

require('tools.js')();

然后

sum(1,2);

在我的情况下,我有一个文件与控制器ctrl .js

module.exports = function() {
    this.Categories = require('categories.js');
}

和我可以使用类别在每个上下文后的公共类require('ctrls.js')()

其他回答

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

我也在寻找一个选项,包括代码而不编写模块,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'
    }

}

希望这对你有所帮助。

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

function A(){
.
.
.
}

function B(){
.
.
.
}

module.exports = {
A,
B
}

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

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

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

比如你有一个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中包含所有文件而不是传递它。

谢谢