createReadStream在同一个fd上多次

在前面的问题中 ,似乎从node.js中的文件中进行随机访问读取的唯一方法是使用带有可选fdstartend字段的fs.createReadStream()

这在我最简单的testing中工作得很好。 但在我的项目中,我需要反复读取二进制文件的不同偏移量。 这是一个奇怪的方式,所以我想出了一个最小的testing用例:

 var fs = require('fs'); fs.open('test.txt', 'r', function (err, fd) { if (err) { console.error('error opening file: ' + err); } else { fs.createReadStream(null, {fd: fd, start: 2, end: 5}).on('error', function (err) { throw e; }).on('close', function () { console.log('outer close'); }).on('data', function (data) { console.log('outer data', data); }).on('end', function () { console.log('outer end'); fs.createReadStream(null, {fd: fd, start: 0, end: 3}).on('error', function (err) { throw e; }).on('close', function () { console.log('inner close'); }).on('data', function (data) { console.log('inner data', data); }).on('end', function () { console.log('inner end'); // more code to execute after both reads }); }); } }); 

内部end事件从来没有收到。 (外部收不一致,但我不需要附加代码。)

我之前已经在Perl中实现了这个项目,甚至在Firefox中作为Firefox扩展实现了这个项目,但是在节点之下certificate是困难的。 这也是我是否可以开始使用node.js作为通用脚本语言的testing 。

问题是,外部ReadStream将在使用后closuresfd ,因此在第二个ReadStream上重新使用它将会失败。 最新的Node不稳定实际上有一个autoClose选项,但这不是稳定的一部分。

真正的答案是,你在上一个问题中提供给你的信息是不正确的。 createReadStream是使用所有公共API实现的,所以没有办法做到这一点。 在这种情况下,你可以使用fs.readposition参数。

 var fs = require('fs'); fs.open('test.txt', 'r', function (err, fd) { if (err) { console.error('error opening file: ' + err); } else { fs.read(fd, new Buffer(4), 0, 4, 2, function(err, bytesRead, data){ if (err) throw err; console.log('outer data', data); fs.read(fd, new Buffer(3), 0, 3, 0, function(err, bytesRead, data2){ if (err) throw err; console.log('inner data', data2); fs.close(fd); // more code to execute after both reads }); }); } });