节点。不获取数据的可读文件流

时间:2021-11-27 14:07:17

I'm attempting to create a Readable file stream that I can read individual bytes from. I'm using the code below.

我正在尝试创建一个可读的文件流,我可以从中读取单个字节。我正在使用下面的代码。

var rs = fs.createReadStream(file).on('open', function() {
    var buff = rs.read(8); //Read first 8 bytes
    console.log(buff);
});

Given that file is an existing file of at least 8 bytes, why am I getting 'null' as the output for this?

假设这个文件是一个至少有8字节的现有文件,为什么我要将'null'作为这个文件的输出呢?

2 个解决方案

#1


4  

Event open means that stream has been initialized, it does not mean you can read from the stream. You would have to listen for either readable or data events.

事件打开意味着流已经初始化,并不意味着您可以从流中读取。您必须侦听可读或数据事件。

var rs = fs.createReadStream(file);

rs.once('readable', function() {
    var buff = rs.read(8); //Read first 8 bytes only once
    console.log(buff.toString());
});

#2


0  

It looks like you're calling this rs.read() method. However, that method is only available in the Streams interface. In the Streams interface, you're looking for the 'data' event and not the 'open' event.

看起来您正在调用这个rs.read()方法。但是,该方法仅在Streams接口中可用。在Streams接口中,您寻找的是“数据”事件,而不是“打开”事件。

That stated, the docs actually recommend against doing this. Instead you should probably be handling chunks at a time if you want to stream them:

这说明,医生实际上建议不要这样做。相反,如果你想要流数据的话,你应该一次处理一些数据块:

var rs = fs.createReadStream('test.txt');

rs.on('data', function(chunk) {
    console.log(chunk);
});

If you want to read just a specific portion of a file, you may want to look at fs.open() and fs.read() which are lower level.

如果您只想读取文件的特定部分,您可能需要查看较低级别的fs.open()和fs.read()。

#1


4  

Event open means that stream has been initialized, it does not mean you can read from the stream. You would have to listen for either readable or data events.

事件打开意味着流已经初始化,并不意味着您可以从流中读取。您必须侦听可读或数据事件。

var rs = fs.createReadStream(file);

rs.once('readable', function() {
    var buff = rs.read(8); //Read first 8 bytes only once
    console.log(buff.toString());
});

#2


0  

It looks like you're calling this rs.read() method. However, that method is only available in the Streams interface. In the Streams interface, you're looking for the 'data' event and not the 'open' event.

看起来您正在调用这个rs.read()方法。但是,该方法仅在Streams接口中可用。在Streams接口中,您寻找的是“数据”事件,而不是“打开”事件。

That stated, the docs actually recommend against doing this. Instead you should probably be handling chunks at a time if you want to stream them:

这说明,医生实际上建议不要这样做。相反,如果你想要流数据的话,你应该一次处理一些数据块:

var rs = fs.createReadStream('test.txt');

rs.on('data', function(chunk) {
    console.log(chunk);
});

If you want to read just a specific portion of a file, you may want to look at fs.open() and fs.read() which are lower level.

如果您只想读取文件的特定部分,您可能需要查看较低级别的fs.open()和fs.read()。