Q:

How to read a file and update the file at particular line with nodejs script

I want to create a node script to generate set of folders and file and write some starting code to it like we have cli commands from angular. I have a file called screen_names.js, whenever a new screen is created by running command npm run feature [featureName], a folder with some sub folders and files are created inside the feature folder in may application and i want to add and import statement after all others import statements in the file and add an export state after all other export statement in the file.
import Input from '../features/Input/containers'
import Segment from '../features/segment/containers'
....
// add an import state here

export {
...,
    Input,
    Segment,
// add export component name here
}

How can i read this file and append at appropriate positions and save the file again in javascript.

A:

You can read the file line by line using readline module and check for particular condition to update and once all the data is read then write it into the same file using fs module.
index.js
var output = "";
var fs = require('fs');
var lineReader = require('readline').createInterface({
  input: require('fs').createReadStream('file.txt')
});

lineReader.on('line', function (line) {
  if(CONDITON_TO_CHECK_FOR_UPDATE){

  }
  output += line + "\n";
});

lineReader.on('close', function (line) {
  fs.writeFile('file.txt', output, function(err, data){
    if (err) console.log(err);
    console.log("Successfully Written to File.");
});
});

