Readline.write创建空白文件

时间:2017-08-21 18:39:07

标签: node.js

尝试从一个文件写入另一个文件。当我登录日志时,我可以看到.write被一致地调用。转换后的文件已创建,但是当我打开文件时它是空的。控制台日志显示我可以看到正确的行数据。我在这做错了什么?

以下代码段:

var fileRebuilder = readline.createInterface({
    input: fs.createReadStream('./' + directory + file),
    output: fs.createWriteStream('./' + directory + 'Converted' + file),
});
var lineRead = 0;
fileRebuilder.on('line', function (line) {
    lineRead++;
    if (linesForRemoval.indexOf(lineRead) > -1) {
    } else {
        fileRebuilder.write(line);
    }
}).on('close', function () {
    fileRebuilder.close();
});

1 个答案:

答案 0 :(得分:1)

你需要:

fileRebuilder.output.write(line + "\n");

工作示例:

const readline = require('readline');
const fs = require('fs');
function FileRebuilder(directory,file,linesForRemoval){
  const fileRebuilder = readline.createInterface({
      input: fs.createReadStream(directory + '/' + file),
      output: fs.createWriteStream(directory + '/converted-' + file),
  });
  console.log("[fileRebuilder]","start");
  var lineRead = 0;
  fileRebuilder.on('line', function (line) {
      lineRead++;
      if (linesForRemoval.indexOf(lineRead) > -1) {
        console.log("@[ line",lineRead,"]","removing!");
      } else {
        console.log("@[ line",lineRead,"]","writing!");
        fileRebuilder.output.write(line + "\n");
      }
  }).on('close', function () {
    console.log("[fileRebuilder]","closed");
    fileRebuilder.close();
  });
}

 FileRebuilder(__dirname,'sample.txt',[4,8]);