1

Am writing a to a file by taking input from terminal. however, when I tried to listen to the text "exit" so that I can exit the program. the listener is not triggered.

I have written the code. I am already getting the input via the terminal and writing to a file. However. I cannot exit the program

const fs = require('fs');
const writeStream = fs.createWriteStream('./myFile.txt', 'utf8');

process.stdin.on('data', (data, done) => {
    if (data === 'exit') {
        done();
    }
    writeStream.write(data);

});

process.on('exit', () => {
    process.exit();
}); 

from terminal window: input text to write to file: 1.This is my test text 2. I am writing this to file 3. exit

Expected result: I expect the lines 1 and 2 to be written to file and as soon as the exit word is typed. the program should exit. Actual: This is not the case as the word 'exit' is also added to the file and the program refused to exit except I press a key combination of CTRL + C.

1
  • Could it be a matter of newline / carriage return data == 'exit\n'? Commented Aug 7, 2019 at 15:53

2 Answers 2

2
process.stdin.on('data', (data, done) => {
    if (data === 'exit' or data === 'exit\n') { 
        process.exit();
    }else {
        writeStream.write(data);
    }
});

you need to wrap the writeStream.write(data); in a else statment and use process.exit() instead of done. also look for exit\n not just exit

Sign up to request clarification or add additional context in comments.

3 Comments

@graficode thats the idea, he doesnt want exit to be writen into the file
It shouldn't write to file if it exts first
@JimiHunter can you please elaborate? did you receive errors? or did it not do the function it should?
1

From this post. Hope it might help you.

Calling process.exit() will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations to process.stdout and process.stderr.

To properly exit the code while letting the process exit gracefully, edit your code with the below in the exit process.

if (someConditionNotMet()) {
  printUsageToStdout();  
  process.exitCode = 1;
}

Comments

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.