[英]How do I do random access reads from (large) files using node.js?
Am I missing something or does node.js's standard file I/O module lack analogs of the usual file random access methods? 我错过了什么或者node.js的标准文件I / O模块缺少通常的文件随机访问方法的类似物吗?
seek()
/ fseek()
seek()
/ fseek()
tell()
/ ftell()
tell()
/ ftell()
How does one read random fixed-size records from large files in node without these? 如何从没有这些的节点中的大文件中读取随机固定大小的记录?
tell
is not, but it is pretty rare to not already know the position you are at in a file, or to not have a way to keep track yourself. tell
不是,但很少有人知道你在文件中的位置,或者没有办法自己跟踪。
seek
is exposed indirectly via the position
argument of fs.read
and fs.write
. seek
通过fs.read
和fs.write
的position
参数间接暴露。 When given, the argument will seek to that location before performing its operation, and if null
, it will use whatever previous position it had. 给定时,参数将在执行其操作之前寻找该位置,如果为
null
,则它将使用它具有的任何先前位置。
node doesn't have these built in, the closest you can get is to use fs.createReadStream
with a start
parameter to start reading from an offset, (pass in an existing fd
to avoid re-opening the file). 节点没有这些内置,你可以得到的最接近的是使用带有
start
参数的fs.createReadStream
来开始从偏移读取,(传入现有的fd
以避免重新打开文件)。
http://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options http://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options
I suppose that createReadStream creates new file descriptor over and over. 我想createReadStream一遍又一遍地创建新的文件描述符。 I prefer sync version:
我更喜欢同步版本:
function FileBuffer(path) {
const fd = fs.openSync(path, 'r');
function slice(start, end) {
const chunkSize = end - start;
const buffer = new Buffer(chunkSize);
fs.readSync(fd, buffer, 0, chunkSize, start);
return buffer;
}
function close() {
fs.close(fd);
}
return {
slice,
close
}
} }
Use this: 用这个:
fs.open(path, flags[, mode], callback)
Then this: 然后这个:
fs.read(fd, buffer, offset, length, position, callback)
Read this for details: 阅读本文了解详情:
https://nodejs.org/api/fs.html#fs_fs_read_fd_buffer_offset_length_position_callback https://nodejs.org/api/fs.html#fs_fs_read_fd_buffer_offset_length_position_callback
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.