readline rl.write 如何工作? [英] How does readline rl.write work?

查看:27
本文介绍了readline rl.write 如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析一个文件,并将foobar"行替换为bazbar"行.它只是返回一个空文件.我不知道我做错了什么,文档也没有特别的帮助.

I'm trying to parse over a file, and replace lines that say "foobar" with lines that say "bazbar". It just returns an empty file. I have no idea what I'm doing wrong and docs aren't being particularly helpful.

var readline = require('readline');
var fs = require('fs');

var rl = readline.createInterface({
  input: fs.createReadStream('test/in.txt'),
  output: fs.createWriteStream('test/out.txt', {
    flags: 'r+'
  })
});

rl.on('line', function (line) {
  if (line.match(/foobar/)) {
    rl.write(line.replace(/foo/, 'baz'));
  }
});

如果有人有兴趣简单地拉动和弄乱它,这里是 tmp 存储库:https://github.com/corysimmons/css-body-components/tree/master/test

Here's the tmp repo if anyone is interested in simply pulling and messing with it: https://github.com/corysimmons/css-body-components/tree/master/test

推荐答案

这可能无法回答您的问题,但可以完成任务.

This may not answer your question, but it accomplishes the task.

我无法让 rl.write 对文件 WriteStream 起作用,但我确实通过直接写入文件 WriteStream 使其工作> 代替.代码如下:

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()
})

rl.write 只会写入 TTY

查看readline<的源代码/code>,Node 正在检查 output 中提供的流是否为终端.如果是,它会写入流,如果不是,它看起来像是将写入作为 line 事件重新发出.

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.

这意味着您必须欺骗 readline 模块,使其认为您的 fs.WriteStream 实际上是一个 TTY.这是一些有效的更新代码.注意第 5 行添加了一个 isTTY 属性并将其设置为 true.

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')
});

这篇关于readline rl.write 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆