JS:为什么fs.readFileSync()返回缓冲区,即使我之前使用toString()将其转换为字符串?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS:为什么fs.readFileSync()返回缓冲区,即使我之前使用toString()将其转换为字符串?相关的知识,希望对你有一定的参考价值。

希望你很好。

简而言之:我的目标是读取我通过对话框提取的文件。 filepath存储在名为files的对象中。可以使用键files.filePaths提取路径。我想读取该文件(这是一个简单的文本文件)的输入,并将其转换为字符串。

const content = fs.readFileSync(files.filePaths.toString())      // here i converted it into a string
console.log(content)   // however, returns a Buffer Object

console.log(content.toString())       // This however returns the string.

有人知道为什么在这种情况下我必须两次使用toString()吗?

非常感谢。

最佳团员

答案

您传递到readFileSync的文件path是与readFileSync的返回值不同的值(除非您提供编码选项,否则它是一个缓冲区,除非(作为the documentation says)。]]

以上是关于JS:为什么fs.readFileSync()返回缓冲区,即使我之前使用toString()将其转换为字符串?的主要内容,如果未能解决你的问题,请参考以下文章