Get data from fs.readFile

前端 未结 15 2364
滥情空心
滥情空心 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:27

    This line will work,

    const content = fs.readFileSync('./Index.html', 'utf8');
    console.log(content);
    
    0 讨论(0)
  • 2020-11-22 16:29
    function readContent(callback) {
        fs.readFile("./Index.html", function (err, content) {
            if (err) return callback(err)
            callback(null, content)
        })
    }
    
    readContent(function (err, content) {
        console.log(content)
    })
    
    0 讨论(0)
  • 2020-11-22 16:32

    Using Promises with ES7

    Asynchronous use with mz/fs

    The mz module provides promisified versions of the core node library. Using them is simple. First install the library...

    npm install mz
    

    Then...

    const fs = require('mz/fs');
    fs.readFile('./Index.html').then(contents => console.log(contents))
      .catch(err => console.error(err));
    

    Alternatively you can write them in asynchronous functions:

    async function myReadfile () {
      try {
        const file = await fs.readFile('./Index.html');
      }
      catch (err) { console.error( err ) }
    };
    
    0 讨论(0)
提交回复
热议问题