简体   繁体   English

Node.js 同步读取文件作为字符串(不是缓冲区)

[英]Node.js read a file as a string (not buffer) synchronously

How do I read a file in Node.js as a string and not as a buffer?如何将 Node.js 中的文件作为字符串而不是缓冲区读取? I'm making a program in Node.js. There I need to read a file synchronously, but if I do that, it returns it as a buffer instead of a string.我正在 Node.js 中制作一个程序。我需要同步读取一个文件,但如果我这样做,它会将它作为缓冲区而不是字符串返回。 My code looks like that:我的代码看起来像这样:

const fs = require('fs');

let content = fs.readFileSync('./foo.txt');
console.log(content) // actually logs it as a buffer

Please help.请帮忙。

fs.readFileSync takes a second parameter that allows you to specify an object with options, including the encoding of the returned data. fs.readFileSync采用第二个参数,允许您使用选项指定 object,包括返回数据的编码。 If you do not specify one, it returns a Buffer by default.如果不指定,则默认返回一个Buffer So, you would add the encoding to this example to return it as a String.因此,您可以将编码添加到此示例以将其作为字符串返回。

Let's add the encoding option to this example where we set the content variable.让我们在设置content变量的示例中添加编码选项。 We'll set the encoding to be UTF-8, which is a standard.我们将编码设置为 UTF-8,这是一个标准。

let content = fs.readFileSync('./foo.txt', {encoding: 'utf8'});

There is also a shortcut if you do not need to specify any other options:如果您不需要指定任何其他选项,还有一个快捷方式:

let content = fs.readFileSync('./foo.txt', 'utf8');

Now when we log content , we should have a String as the result which we use.现在当我们记录content时,我们应该有一个String作为我们使用的结果。

Official Documentation: https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options官方文档: https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options

Aside from passing encoding which will ensure you get a string and not a buffer, the options parameter of the fs.readFileSync function also allows you to pass in a flag.除了传递确保您获得字符串而不是缓冲区的编码之外,fs.readFileSync function 的选项参数还允许您传递标志。

The default flag of this method is "r", which opens the file for reading.此方法的默认标志是“r”,它打开文件进行读取。 If you're opening it for reading and writing, then you should pass in another flag - "r+".如果你打开它进行读写,那么你应该传入另一个标志 - “r+”。

Your code would look like this if you're opening the file for reading and writing and not just reading:如果您打开文件进行读写而不仅仅是阅读,您的代码将如下所示:

const content = fs.readFileSync('./foo.txt/', 'utf-8', 'r+');
console.log(content);

Since this is node.js, you should consider using the async fs.readFile function instead.由于这是 node.js,您应该考虑改用 async fs.readFile function。 You'll have to pass this a callback of course.当然,您必须将其传递给回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM