In Node.js, how do I “include” functions from my other files?

后端 未结 25 3157
猫巷女王i
猫巷女王i 2020-11-22 04:22

Let\'s say I have a file called app.js. Pretty simple:

var express = require(\'express\');
var app = express.createServer();
app.set(\'views\', __dirname + \         


        
25条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 05:03

    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

提交回复
热议问题