使用Node.js中的through2将数据发送到流时的额外换行符

时间:2015-09-30 13:33:21

标签: node.js stream stdout stdin

我正在经历NodeSchool的溪流冒险研讨会。我是编写一个程序,将process.stdin流传输到使用through2模块创建的流,然后将其传递给process.stdout。使用through2模块创建的流将输入流字符转换为大写并将其传递给process.stdout。以下是我的源代码:

var through = require('through2');
var write = function(buffer,encoding,next){
        var data = buffer.toString();
        this.push(data.toUpperCase() + '\n');
        next();
}
var end = function (done){
        done();
}
var stream = through(write,end);
process.stdin.pipe(stream).pipe(process.stdout);

问题是,在每8个字块发送到流中后,会打印一个额外的换行符。以下是研讨会所做验证的3个测试结果:

测试1:

TAP version 13
# (anonymous)
ok 1 stream-adventure verify YOURFILE.js
not ok 2 should be equal
  ---
    operator: equal
    expected:
      'METALKIND\nKORVEN\nOSIRIAN\nTHE ERGON\nTYTHONIAN\nLAND OF FICTION BEINGS\nSIRIAN\nKRAAL\nTHE FLOOD\nJADONDAN\n'
    actual:
      'METALKIND\nKORVEN\nOSIRIAN\nTHE ERGON\nTYTHONIAN\nLAND OF FICTION BEINGS\nSIRIAN\nKRAAL\n\nTHE FLOOD\n\nJADONDAN\n\n'
  ...
ok 3 successful exit code

1..3
# tests 3
# pass  2
# fail  1

#########################################
###   YOUR SOLUTION IS NOT CORRECT!   ###
#########################################

测试2:

TAP version 13
# (anonymous)
ok 1 stream-adventure verify YOURFILE.js
not ok 2 should be equal
  ---
    operator: equal
    expected:
      'THE BEAST\nANDROZANI TREE\nGAZTAK\nRAXACORICOFALLAPATORIAN\nMAYFLY\nSTIGORAX\nTHE TRICKSTER\nMEGARA\nMENTOR\nHAND OF OMEGA\n'
    actual:
      'THE BEAST\nANDROZANI TREE\nGAZTAK\nRAXACORICOFALLAPATORIAN\nMAYFLY\nSTIGORAX\nTHE TRICKSTER\nMEGARA\nMENTOR\n\nHAND OF OMEGA\n\n'
  ...
ok 3 successful exit code

1..3
# tests 3
# pass  2
# fail  1

#########################################
###   YOUR SOLUTION IS NOT CORRECT!   ###
#########################################

测试3:

TAP version 13
# (anonymous)
ok 1 stream-adventure verify YOURFILE.js
not ok 2 should be equal
  ---
    operator: equal
    expected:
      'QETESH\nPELUSHI\nLURMAN\nEVE\nATRAXI\nFLESHKIND\nDALEK\nGEE-JEE FLY\nHEADLESS MONK\nTHE DESTROYER\n'
    actual:
      'QETESH\nPELUSHI\nLURMAN\nEVE\nATRAXI\nFLESHKIND\nDALEK\nGEE-JEE FLY\n\nHEADLESS MONK\n\nTHE DESTROYER\n\n'
  ...
ok 3 successful exit code

1..3
# tests 3
# pass  2
# fail  1

#########################################
###   YOUR SOLUTION IS NOT CORRECT!   ###
#########################################

神秘的额外换行的原因是什么?如何解决?

2 个答案:

答案 0 :(得分:1)

您的代码中第4行添加了额外的换行符。要解决此问题,您可以更改第4行:

this.push(data.toUpperCase() + '\n');

到此:

this.push(data.toUpperCase());

当你在终端

中输入时,流冒险课程将打印他们的参考解决方案
stream-adventure solution 

答案 1 :(得分:0)

不要添加'\ n'它已经在流中。我猜你得到的缓冲区不止一行,所以'\ n'是随机添加的。