简体   繁体   English

用 Node.js stream 读取二进制数据

[英]Read binary data with Node.js stream

I'm trying to read a binary file with fs createReadStream .我正在尝试使用 fs createReadStream读取二进制文件。 Assumed that we know the "misunderstanding" of binary and latin1 as value for the encoding option, and that by defaults using toString on the data chunk will use utf-8 , I have tried to user a Buffer and buffer concatenation that is the .concat function in this way:假设我们知道binarylatin1作为encoding选项的值的“误解”,并且默认情况下在data块上使用toString将使用utf-8 ,我尝试使用Buffer和缓冲区连接,即.concat function这边走:

 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); })

so that to append the new chunk to the data.以便 append 将新块添加到数据中。 In this way the typeof object in data is object , but it seems the encoding it is still not a binary format (ie it is not application/octet-stream charset=binary to be clear in terms of content type.)这样, data中的typeof的类型是object ,但似乎编码它仍然不是二进制格式(即它不是application/octet-stream charset=binary就内容类型而言要明确。)

If I just do data+=chunk the output type will be string .如果我只是做data+=chunk ,则 output 类型将是string

If the data coming out of the file is already 'binary' encoding, then set the readStream encoding to 'binary' using setEncoding() and concatenate all of the chunks into a single string and return that.如果来自文件的数据已经是'binary'编码,则使用setEncoding()readStream编码设置为'binary'并将所有块连接到单个 string 并返回。 setEncoding() supports any of the encodings implemented in Node per Buffer docs for Encodings. setEncoding()支持在 Node per 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) }) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM