使用Node.js将整个文件缓冲在内存中 [英] Buffer entire file in memory with Node.js

查看:329
本文介绍了使用Node.js将整个文件缓冲在内存中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相对较小的文件(大约数百KB),我想将其保存在内存中以直接访问整个代码执行过程。

I have a relatively small file (some hundreds of kilobytes) that I want to be in memory for direct access for the entire execution of the code.

我不确定Node.js的内部结构,所以我问一个 fs打开是否足够,或者我必须读取所有文件并复制到一个 Buffer

I don't know exactly the internals of Node.js, so I'm asking if a fs open is enough or I have to read all file and copy to a Buffer?

推荐答案

基本上,您需要使用 readFile fs 模块中的$ c>或 readFileSync 函数。它们返回给定文件的完整内容,但是行为不同(异步还是同步)。

Basically, you need to use the readFile or readFileSync function from the fs module. They return the complete content of the given file, but differ in their behavior (asynchronous versus synchronous).

如果阻塞Node.js(例如,在应用程序启动时)没问题,您可以使用同步版本,它很简单:

If blocking Node.js (e.g. on startup of your application) is not an issue, you can go with the synchronized version, which is as easy as:

var fs = require('fs');

var data = fs.readFileSync('/etc/passwd');

如果您需要异步处理,则代码如下:

If you need to go asynchronous, the code is like that:

var fs = require('fs');

fs.readFile('/etc/passwd', function (err, data ) {
  // ...
});

请注意,无论哪种情况,您都可以给出选项对象作为第二个参数,例如指定要使用的编码。如果您省略编码,则会返回原始缓冲区:

Please note that in either case you can give an options object as the second parameter, e.g. to specify the encoding to use. If you omit the encoding, the raw buffer is returned:

var fs = require('fs');

fs.readFile('/etc/passwd', { encoding: 'utf8' }, function (err, data ) {
  // ...
});

有效编码为 utf8 ascii utf16le ucs2 base64 hex 。还有一个 binary 编码,但已弃用,不应再使用。您可以在相应的文档中找到有关如何处理编码和缓冲区的更多详细信息。

Valid encodings are utf8, ascii, utf16le, ucs2, base64 and hex. There is also a binary encoding, but it is deprecated and should not be used any longer. You can find more details on how to deal with encodings and buffers in the appropriate documentation.

这篇关于使用Node.js将整个文件缓冲在内存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆