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


当前回答

创建两个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

其他回答

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

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

如果,不管所有其他答案,你仍然想传统地在node.js源文件中包含一个文件,你可以使用这个:

var fs = require('fs');

// file is included here:
eval(fs.readFileSync('tools.js')+'');

为了将文件内容作为字符串而不是对象获取,必须使用空字符串连接+ "(如果您愿意,也可以使用. tostring())。 eval()不能在函数内部使用,必须在全局作用域内调用,否则没有函数或变量可访问(即不能创建include()实用函数或类似的东西)。

请注意,在大多数情况下,这是不好的做法,您应该编写一个模块。然而,在极少数情况下,您真正想要的是对本地上下文/名称空间的污染。

更新2015-08-06

请注意,这对“use strict”无效;(当你处于“严格模式”时),因为在“导入”文件中定义的函数和变量不能被执行导入的代码访问。严格模式强制执行一些由语言标准的新版本定义的规则。这可能是避免此处描述的解决方案的另一个原因。

创建两个文件,例如app.js和tools.js

app.js

const tools= require("./tools.js")


var x = tools.add(4,2) ;

var y = tools.subtract(4,2);


console.log(x);
console.log(y);

tools.js

 const add = function(x, y){
        return x+y;
    }
 const subtract = function(x, y){
            return x-y;
    }
    
    module.exports ={
        add,subtract
    }

输出

6
2

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

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

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

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