Express.js Mastery / Introduction To Node.js And NPM

Reading and Writing Files Node

πŸ“₯ 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.txt

  • The . means the current folder (where index.js lives).

  • From there, it goes into the txt folder to find input.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:

  1. πŸ“ Path to the file to create/write β€” ./txt/output.txt

  2. πŸ“ The content to write into that file β€” the textOut variable

  • 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

  1. Clear the terminal: Cmd/Ctrl + K or clear

  2. Run the file again:

node index.js

(Or press ⬆️ Up Arrow then Enter.)

  1. πŸ“„ A new file called output.txt will appear inside the txt folder.

  1. πŸ“„ Opening it will show:

    • πŸ“ The custom text you wrote

    • πŸ“– The original content read from input.txt

    • πŸ•’ The current timestamp (from Date.now())