0

I'm trying to write a function that reads a file and when it finds a specific line it deletes everything below it and then it appends another set of lines. I have managed to read the file and find the string I need:

function read() {
    lineReader.on('line', function (line) {
        console.log('Line from file: ' + line)
        if(line.trim() === 'Examples:'){
            console.log('Found what I needed, delete everything below this line');
        }
    });
}

What I'm unable to see is how to delete everything below this line and then append the text I need. I am new to JS and Node.js.

0

1 Answer 1

1

You could do this by opening a file writing stream at the same time.

In the lineReader event handler, put all the lines before "Example" into a separate file stream. When Example comes along, just append your desired set of lines into the second file stream and close the lineReader.

So add something like this:

// before the code
var writer = fs.createWriteStream('new.txt');
// load custom lines from customLines.txt
var customLines = fs.readFileSync('customLines.txt');

// in the on('line') callback:
  writer.write(line + "\n");

// if 'Examples:' was found:
  writer.write(customLines);
  writer.end();
  lineReader.close();
Sign up to request clarification or add additional context in comments.

3 Comments

@jfriend00 it doesn't have to be, hence the sync variation.
@Phix - Well, if it's server code (anywhere other than startup), then it should be async because blocking, synchronous I/O can ruin server scalability.
It doesn't have to be async. fs.readFileSync() will block the execution until the file contents have been slurped into a string. It is shorter to write for a StackOverflow example, and often times works well enough. There are cases where you should prefer the async version, and this includes larger files and production/serverside/scalable usage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.