@beenotung/tslib
Version:
utils library in Typescript
63 lines (62 loc) • 1.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.readStreamByLine = readStreamByLine;
exports.readStreamAllLine = readStreamAllLine;
exports.readStreamAsString = readStreamAsString;
const stream_1 = require("stream");
/**
* @description lineNum start from 0
* */
function readStreamByLine(stream, _onLine, _onError, _onComplete) {
const _lineStream = new stream_1.Stream();
let _lineNum = -1;
let acc = '';
const onLine = (line) => {
_lineNum++;
const data = { line, lineNum: _lineNum };
_lineStream.emit('data', data);
if (_onLine) {
_onLine(line, _lineNum);
}
};
const onError = (e) => {
_lineStream.emit('error', e);
if (_onError) {
_onError(e);
}
};
const onComplete = () => {
if (acc !== '') {
console.warn('stream ends without newline');
onLine(acc);
}
_lineStream.emit('end');
if (_onComplete) {
_onComplete();
}
};
stream.on('data', s => {
acc += s;
const ss = acc.split('\n');
if (ss.length === 1) {
return;
}
const n = ss.length - 1;
for (let i = 0; i < n; i++) {
onLine(ss[i]);
}
acc = ss[n];
});
stream.on('error', onError);
stream.on('end', onComplete);
return _lineStream;
}
function readStreamAllLine(stream) {
return new Promise((resolve, reject) => {
const lines = [];
readStreamByLine(stream, line => lines.push(line), e => reject(e), () => resolve(lines));
});
}
function readStreamAsString(stream, lineFeed = '\n') {
return readStreamAllLine(stream).then(lines => lines.join(lineFeed));
}