在Node.js中,如何从其他文件中“包含”函数?

假设我有一个名为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文件进行基本导入。

小哥Pro梅2020/03/13 18:07:20

Use:

var mymodule = require("./tools.js")

app.js:

module.exports.<your function> = function () {
    <what should the function do>
}
小卤蛋卡卡西A2020/03/13 18:07:20

Like you are having a file abc.txt and many more?

Create 2 files: fileread.js and fetchingfile.js, then in fileread.js write this code:

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

In fetchingfile.js write this code:

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

Now, in a terminal: $ node fetchingfile.js --file=abc.txt

You are passing the file name as an argument, moreover include all files in readfile.js instead of passing it.

Thanks

宝儿LEY理查德2020/03/13 18:07:20

您可以将函数放在全局变量中,但是最好将工具脚本转换为模块。其实并不太难–只需将公共API附加到exports对象即可。请看一下了解Node.js的导出模块了解更多详细信息。

2020/03/13 18:07:19

创建两个文件,例如app.jstools.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
Pro理查德LEY2020/03/13 18:07:19

说我们要调用函数平()添加(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
    }
伽罗小哥2020/03/13 18:07:19

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