DimlyAware DimlyAware - 2 months ago 15
Node.js Question

Readline.write creating blank file

Trying to write from one file to the other. When i console log i can see that .write is being called consistently. The converted file is created but when i open the file its empty. Console log shows i can see the correct line data. What am i doing wrong here?

Code snippet below:

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

EMX EMX
Answer Source

You needed :

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

Working example :

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]);