我正在编写一个小型解析器来使用节点流(实际上是 io.js,但我认为这并不重要)来处理一些日志文件。
我正在按照文档中的示例进行 unshift来解析标题。我可以成功拆分缓冲区并获取标题,但是一旦我调用stream.unshift
它,它似乎就会连接标题字符串和剩余的字符串。
在为这个问题设置一些示例代码时,我发现当我查看基于文件的流时会发生这种行为。每当我使用基于字符串的流时,即使文件具有与字符串完全相同的文本,问题也不会发生。
这是我的文本编辑器中打开了空白字符的文件的样子,(用于比较):
我需要一些帮助来理解为什么会这样。
var StringDecoder = require('string_decoder').StringDecoder;
// setup string based stream in fake_stream
var Stream = require('stream');
var fake_file = 'FILE_TYPE:SOME-HEADER-DATE\r\n'
+ 'HEADER_END\r\n'
+ '1234|logged data|1|2|3|4|5|some other logged data\x1E\r\n'
+ '1235|logged data|1|2|3|4|5|some other logged data\x1E\r\n'
+ '1236|logged data|1|2|3|4|5|some other logged data\x1E\r\n'
var fake_stream = new Stream.Readable();
fake_stream.push(new Buffer(fake_file, 'utf8'));
fake_stream.push(null);
// setup file based stream in file_stream
// the file minimal_test_log.glf has the text shown above (with the control characters unescaped)
var fs = require('fs');
var file = 'C:\\Some\\Path\\To\\minimal_test_log.glf';
var file_stream = fs.createReadStream(file);
// WHY AM I GETTING DIFFERENT RESULTS HERE?
parseHeader(file_stream, function(err, header, stream) {
console.log('processing file_stream: ' + header.length);
// RESULTS: processing file_stream: 184
// this results in the both parts concatenated without the HEADER_END/r/n
});
parseHeader(fake_stream, function(err, header, stream) {
console.log('processing fake_stream: ' + header.length);
// RESULTS: processing fake_stream: 28
// these results are what i would expect, everything before HEADER_END
});
// Slightly modified example found at https://iojs.org/api/stream.html#stream_readable_unshift_chunk
function parseHeader(stream, callback) {
stream.on('error', callback);
stream.on('readable', onReadable);
var decoder = new StringDecoder('utf8');
var header = '';
function onReadable() {
var chunk, buf, remaining;
var header_boundary = /HEADER_END\r\n/g;
while (null !== (chunk = stream.read())) {
var str = decoder.write(chunk);
if (str.match(header_boundary)) {
var split = str.split(header_boundary);
header += split.shift();
remaining = split.join('');
buf = new Buffer(remaining, 'utf8');
if (buf.length) {
stream.unshift(buf);
}
// the header length is different starting at this point
stream.removeListener('error', callback);
stream.removeListener('readable', onReadable);
callback(null, header, stream);
} else {
header += str;
}
}
}
}