如何在NodeJS中将文件转换为字符串

Moi*_*ish 5 javascript string file readfile node.js

我正在尝试将文本文件(在我的机器上)转换为字符串。最好/最简单的方法是什么?我正在寻找一个看起来像这样的基本功能:

function fileToString(filepath) {
   //this returns a string with the contents of the file
}
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

编辑:我现在知道还有另一个问题会问这个问题,但我不明白那个问题,所以我用不同的词问了它。

Nur*_*yev 12

你需要 node.js 和这个代码:

const fs = require('fs')

const fileContents = fs.readFileSync('./myFile').toString()
Run Code Online (Sandbox Code Playgroud)

  • fs.readFileSync('./myFile', 'utf8') 返回一个字符串。不需要 .toString() https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options (2认同)

Jac*_*ord 7

为此,您需要使用Node.js。代码是:

const fs = require('fs');
const fileName = "myFile.txt";
const fileData = fs.readFileSync(fileName, "utf8");
Run Code Online (Sandbox Code Playgroud)