Why does Node.js' fs.readFile() return a buffer instead of string?

后端 未结 6 978
梦毁少年i
梦毁少年i 2020-11-30 17:33

I\'m trying to read the content of test.txt(which is on the same folder of the Javascript source) and display it using this code:

var fs = requi         


        
6条回答
  •  执念已碎
    2020-11-30 17:56

    The data variable contains a Buffer object. Convert it into ASCII encoding using the following syntax:

    data.toString('ascii', 0, data.length)
    

    Asynchronously:

    fs.readFile('test.txt', 'utf8', function (error, data) {
        if (error) throw error;
        console.log(data.toString());
    });
    

提交回复
热议问题