Yesterday, I learned how to read from a file. Today, I wanted to learn the natural extension of yesterday’s lesson and learn to write to a file! Along the way, I decided I needed to get some input from the command line so I could write dynamic info to my Welcome.txt file.
Just like yesterday, we will be using the fs module bundled with Node. So we start out with
const fs = require('fs');
Next we want to write something new to the file. (WARNING: If you don’t read your file first and append the new data to the old you will overwrite your entire file)
fs.writeFileSync('./Welcome.txt', `\n (${Date.now()}) - Test001`);
Ok, now we just read the file and output it to the console.
console.log(fs.readFileSync('./Welcome.txt', 'utf-8'));
In order to not overwrite your whole file like I did you need to first read in your old file and then prepend that to your string template literal.
const textIn = fs.readFileSync('./Welcome.txt','utf-8');
fs.writeFileSync('./Welcome.txt', `${textIn} \n (${Date.now()}) - NewText001`);
Each time I wanted to add something new to the file I had to change my source code and that was obviously not ideal. So we need a way to input some new text for our file from the command line and luckily we found the readline module. You can import it with the following require statement:
const readline = require("readline");
The next thing we needed to do was to setup a rl variable with an object that contains input and output data. We found this in Node’s documentation here: https://nodejs.org/en/knowledge/command-line/how-to-prompt-for-command-line-input/ and it looks like this:
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
Next we use the rl variable’s question method to set up a question and then pass the input from the command line into a callback function where we write that text input to our file. Inside this callback function we use the rl variable’s close method to stop the input stream. This looks like the following:
rl.question('Journal Entry for Today: ', function(entry) {
fs.writeFileSync('./Welcome.txt', `${textIn} \n (${Date.now()}) - ${entry}`);
rl.close();
});
Finally we want to stop the process and return to the command prompt using the rl variables on method where we pass the phrase “close” and a callback function where we log the resulting text file in the console and then use process.exit to kill the program.
rl.on("close", function() {
console.log("\nBYE BYE !!!");
console.log(fs.readFileSync('./Welcome.txt', 'utf-8'));
process.exit(0);
});
Viola! There we have it.
We read input from the command line and we wrote that input to a file. Tomorrow we may try to loop this until we decide to quit or something else. Not sure. Thanks for reading and following along. Message me on twitter @jasonmziegler