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


当前回答

要把“工具”变成一个模块,我一点也不觉得困难。尽管有其他的答案,我仍然建议使用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 

其他回答

您可以将函数放在全局变量中,但更好的做法是将工具脚本转换为模块。这并不难——只需将您的公共API附加到exports对象。看一看理解Node.js的exports模块,了解更多细节。

假设我们想调用函数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
    }

创建两个JavaScript文件。例如import_functions.js和main.js

1.) import_functions.js

// Declaration --------------------------------------

 module.exports =
   {
     add,
     subtract
     // ...
   }


// Implementation ----------------------------------

 function add(x, y)
 {
   return x + y;
 }

 function subtract(x, y)
 {
   return x - y;
 }
    

// ...

2.) main.js

// include ---------------------------------------

const sf= require("./import_functions.js")

// use -------------------------------------------

var x = sf.add(4,2);
console.log(x);

var y = sf.subtract(4,2);
console.log(y);

    

输出

6
2

使用node.js和express.js框架时的另一种方法

var f1 = function(){
   console.log("f1");
}
var f2 = function(){
   console.log("f2");
}

module.exports = {
   f1 : f1,
   f2 : f2
}

将其存储在一个名为s的js文件中,并保存在statics文件夹中

现在使用这个函数

var s = require('../statics/s');
s.f1();
s.f2();

app.js

let { func_name } = require('path_to_tools.js');
func_name();    //function calling

tools.js

let func_name = function() {
    ...
    //function body
    ...
};

module.exports = { func_name };