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.

2 Answers2

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

Ariel Hurdle
  • 68
  • 1
  • 13
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;
}
coderpc
  • 4,119
  • 6
  • 51
  • 93