Get data from fs.readFile

前端 未结 15 2477
滥情空心
滥情空心 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: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 ) }
    };
    

提交回复
热议问题