π₯ Step 1: Reading a File with fs.readFileSync()
Use the fs module (already imported earlier with require('fs')) to read a file:
const fs = require("fs");
const textIn = fs.readFileSync("./txt/input.txt", "utf8");
console.log(textIn);
This function takes two arguments:
π File path

./txt/input.txtThe
.means the current folder (whereindex.jslives).From there, it goes into the
txtfolder to findinput.txt.
π€ Character encoding
We use
'utf8', which works well for plain text.Skip this argument, and Node gives you a Buffer (raw data) instead of readable text β not what you want here.
βΆοΈ Run It
In the terminal: node index.js
(Tip: press the β¬οΈ Up Arrow to quickly pull up your last command.)
β
You should see the contents of input.txt printed to the console.
βοΈ Step 2: Writing to a File with fs.writeFileSync()
π Create the Content to Write
Use a template string (ES6 feature) to build the text you want to save:
const textOut=`This is what we know about the avocado:${textIn}. Created on${Date.now()}`;πΎ Write the File
fs.writeFileSync('./txt/output.txt', textOut);
console.log('File written!');
This function takes two arguments:
π Path to the file to create/write β
./txt/output.txtπ The content to write into that file β the
textOutvariable
writeFileSync()doesn't return anything meaningful, so there's no need to store its result in a variable.β A
console.log()is added afterward just to confirm the file was written successfully.
π» Full Code:
const fs = require("fs");
const textIn = fs.readFileSync("./txt/input.txt", "utf8");
console.log(textIn);
const textOut = `This is what we know about the avocado:${textIn}. Created on${Date.now()}`;
fs.writeFileSync("./txt/output.txt", textOut);
console.log("File written!");βΆοΈ Run and Verify
Clear the terminal:
Cmd/Ctrl + KorclearRun the file again:
node index.js(Or press β¬οΈ Up Arrow then Enter.)
π A new file called
output.txtwill appear inside thetxtfolder.

π Opening it will show:
π The custom text you wrote
π The original content read from
input.txtπ The current timestamp (from
Date.now())
