使用 NodeJs 在内存中缓冲整个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19705972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Buffer entire file in memory with NodeJs
提问by Leonardo Rossi
I have a relatevely small file (some hundreds of kilobytes) that I want to be in memory for direct access for the entire execution of the code.
我有一个相对较小的文件(大约数百 KB),我想在内存中直接访问代码的整个执行过程。
I don't know exactly the internals of NodeJs, so I'm asking if a fs openis enough or I have to read all file and copy to a Buffer?
我不完全了解 NodeJs 的内部结构,所以我问 afs open是否足够,或者我必须读取所有文件并复制到Buffer?
回答by Golo Roden
Basically, you need to use the readFileor readFileSyncfunction from the fsmodule. They return the complete content of the given file, but differ in their behavior (asynchronous versus synchronous).
基本上,您需要使用模块中的readFileorreadFileSync函数fs。它们返回给定文件的完整内容,但它们的行为不同(异步与同步)。
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:
如果阻塞 Node.js(例如在您的应用程序启动时)不是问题,您可以使用同步版本,这很简单:
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 optionsobject as the second parameter, e.g. to specify the encoding to use. If you omit the encoding, the raw buffer is returned:
请注意,无论哪种情况,您都可以将options对象作为第二个参数,例如指定要使用的编码。如果省略编码,则返回原始缓冲区:
var fs = require('fs');
fs.readFile('/etc/passwd', { encoding: 'utf8' }, function (err, data ) {
// ...
});
Valid encodings are utf8, ascii, utf16le, ucs2, base64and hex. There is also a binaryencoding, 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.
有效编码是utf8,ascii,utf16le,ucs2,base64和hex。还有一种binary编码,但它已被弃用,不应再使用。您可以在相应的文档中找到有关如何处理编码和缓冲区的更多详细信息。
回答by vkurchatkin
As easy as
一样容易
var buffer = fs.readFileSync(filename);
回答by Michael Cole
With Node 0.12, it's possible to do this synchronously now:
使用 Node 0.12,现在可以同步执行此操作:
var fs = require('fs');
var path = require('path');
// Buffer mydata
var BUFFER = bufferFile('../public/mydata');
function bufferFile(relPath) {
return fs.readFileSync(path.join(__dirname, relPath)); // zzzz....
}
fsis the file system. readFileSync()returns a Buffer, or string if you ask.
fs是文件系统。 readFileSync()返回一个缓冲区,如果你问,或者字符串。
fscorrectly assumes relative paths are a security issue. pathis a work-around.
fs正确假设相对路径是一个安全问题。 path是一种变通方法。
To load as a string, specify the encoding:
要加载为字符串,请指定编码:
return readFileSync(path,{ encoding: 'utf8' });

