Get data from fs.readFile

前端 未结 15 2482
滥情空心
滥情空心 2020-11-22 15:38
var content;
fs.readFile(\'./Index.html\', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
});
console.log(content);
         


        
15条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 16:14

    There is actually a Synchronous function for this:

    http://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_encoding

    Asynchronous

    fs.readFile(filename, [encoding], [callback])

    Asynchronously reads the entire contents of a file. Example:

    fs.readFile('/etc/passwd', function (err, data) {
      if (err) throw err;
      console.log(data);
    });
    

    The callback is passed two arguments (err, data), where data is the contents of the file.

    If no encoding is specified, then the raw buffer is returned.


    SYNCHRONOUS

    fs.readFileSync(filename, [encoding])

    Synchronous version of fs.readFile. Returns the contents of the file named filename.

    If encoding is specified then this function returns a string. Otherwise it returns a buffer.

    var text = fs.readFileSync('test.md','utf8')
    console.log (text)
    

提交回复
热议问题