How To Read Data Of A Nodejs Stream Without It Being Lost?
I need to know the encoding of a node stream for which I am using detect-character-encoding module. But the problem is that I can only read encodings of a buffer and not a stream d
Solution 1:
You can build a promise to return both the contents and the charset of the stream:
constcharsetStream = (stream) => newPromise((resolve, reject) => {
const detectCharacterEncoding = require('detect-character-encoding');
let chunks = [];
stream.on('data', (chunk) => {
chunks.push(chunk);
})
stream.on('end', () => {
chunks = Buffer.concat(chunks);
resolve({
content: chunks,
charset: detectCharacterEncoding(chunks)
})
})
stream.on('error', (err) => {
reject(err);
})
});
charsetStream(FileStream)
.then(info => {
console.log('content', info.content);
console.log('charset', info.charset);
})
.catch(console.log);
// You can use the FileStream outside the method but you can use it once !// this is completely different than the "stream" variableFileStream.on('data', (chunk) => {
console.log('FileStream', chunk.toString());
})
Post a Comment for "How To Read Data Of A Nodejs Stream Without It Being Lost?"