想要逐行读取一个字符串,看了readline表示有点小疑问啊,因为readline.createInterface(options)
传进去的input
要求是个流,所以我需要将我的字符串转成文本流,尝试用
var fs = require('fs'),
readline = require('readline');
var Stream = require('stream')
var stream = new Stream()
stream.pipe = function(dest) {
dest.write(mailcontent)
}
stream.pipe(process.stdout)
console.log(process.input);
var rd = readline.createInterface({
input: stream,
output: process.stdout,
terminal: false
});
rd.on('line', function(line) {
console.log(line);
});
会报错,如下:
readline.js:142
input.resume();
^
TypeError: Object #<Stream> has no method 'resume'
at new Interface (readline.js:142:9)
at Object.exports.createInterface (readline.js:39:10)
at Readable.<anonymous> (D:\mynodejs\node-server\mailUtil.js:66:47)
at Readable.g (events.js:180:16)
at Readable.EventEmitter.emit (events.js:92:17)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
是不是我哪儿理解错了啊?
2 回复
看起来应该是由String构造的Stream有些问题。 用fs.createReadStream
构造的没有问题。
var readline = require('readline'),
fs = require('fs');
var rl = readline.createInterface({
input: fs.createReadStream(__filename),
output: process.stdout,
terminal: false
});
rl.on('line', function(line) {
console.log('> ' + line);
// you won't see the last line here, as
// there is no \n any more
});