使用Node.js流读取二进制数据

时间:2017-11-07 14:28:42

标签: node.js encoding binary

我试图用fs createReadStream读取二进制文件。假设我们知道"误解" binarylatin1的值作为encoding选项的值,默认使用toString块上的data将使用utf-8,I尝试以这种方式使用Buffer和缓冲连接作为.concat函数:

var readStream = fs.createReadStream( graphPath );
                        var data;
                        readStream.on('data', (chunk) => {
                            var b = new Buffer (chunk.length);
                            if(!data) data = new Buffer (chunk.length);
                            else data = Buffer.concat([data, b]);
                        })  
                        readStream.on('end', () => {
                            console.log( "type is", typeof (data ) );
                            console.log("read graph %d",data.length);data.buffer);
                        });

以便将新块附加到数据中。这样,typeof中的data对象为object,但似乎编码仍然不是二进制格式(即,application/octet-stream charset=binary不清晰内容类型。)

如果我只是data+=chunk,输出类型将是string

1 个答案:

答案 0 :(得分:3)

如果文件中的数据已经是'binary'编码,请使用setEncoding()readStream编码设置为'binary',并将所有块连接成一个字符串并返回。 setEncoding()支持每个Buffer docs for Encodings.

节点中实现的任何编码
const getBinary = (graphPath, asBuffer = false, cb) => {
  let readStream = fs.createReadStream(graphPath)
  let data = ''

  // set stream encoding to binary so chunks are kept in binary
  readStream.setEncoding('binary')
  readStream.once('error', err => {
    return cb(err)
  })
  readStream.on('data', chunk => (data += chunk))
  readStream.on('end', () => {
    // If you need the binary data as a Buffer
    // create one from data chunks       
    return cb(null, asBuffer ? Buffer.from(data, 'binary') : data)
  })
}