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

查看:21
本文介绍了使用 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 open 是否足够,或者我必须读取所有文件并复制到 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?

推荐答案

基本上,你需要使用 fs 中的 readFilereadFileSync 函数代码> 模块.它们返回给定文件的完整内容,但行为不同(异步与同步).

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 ) {
  // ...
});

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

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 ) {
  // ...
});

有效编码为 utf8asciiutf16leucs2base64hex.还有一种 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天全站免登陆