我试图用fs createReadStream
读取二进制文件。假设我们知道"误解" binary
和latin1
的值作为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
。
答案 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)
})
}