This may not answer your question, but it accomplishes the task.
I couldn't get rl.write
to work against a file WriteStream
but I did get it working by writing directly to the file WriteStream
instead. Here's the code:
var readline = require('readline');
var fs = require('fs');
var ws = fs.createWriteStream(__dirname + '/test/out.txt', { flags: 'r+', defaultEncoding: 'utf8' })
var rl = readline.createInterface({
input: fs.createReadStream(__dirname + '/test/in.txt')
});
rl.on('line', function (line) {
if (line.match(/foobar/)) {
line = line.replace(/foo/, 'baz');
}
ws.write(line + '\n');
});
rl.on('close', function() {
ws.close()
})
Edit: rl.write
will only write to a TTY
Looking at the source for readline
, Node is checking if the stream provided in output
is a terminal. If it is, it writes to the stream, if not, it looks like it will re-emit the writes as line
events.
Which means you must trick the readline
module into thinking that your fs.WriteStream
is actually a TTY. Here is some updated code that works. Note line 5 adds an isTTY
property and sets it to true
.
var readline = require('readline');
var fs = require('fs');
var ws = fs.createWriteStream(__dirname + '/test/out.txt', { flags: 'r+', defaultEncoding: 'utf8' })
ws.isTTY = true
var rl = readline.createInterface({
input: fs.createReadStream(__dirname + '/test/in.txt'),
output: ws
});
rl.on('line', function (line) {
var ln
if (line.match(/foobar/)) {
ln = line.replace(/foo/, 'baz')
}
rl.write(ln, '\n')
});