0
0
Node.jsframework~30 mins

Why file system access matters in Node.js - See It in Action

Choose your learning style9 modes available
Why file system access matters
📖 Scenario: You are building a simple Node.js app that reads and writes text files on your computer. This helps you understand why file system access is important for many real-world apps like note-taking, data logging, or configuration management.
🎯 Goal: Create a Node.js script that reads a text file, counts the number of words, and writes the count to a new file.
📋 What You'll Learn
Use the built-in fs module to read and write files
Read the contents of a file named input.txt
Count the number of words in the file content
Write the word count to a file named output.txt
💡 Why This Matters
🌍 Real World
Many apps need to read and save data on your computer, like text editors, loggers, or configuration tools. Understanding file system access lets you build these apps.
💼 Career
Node.js developers often work with files for data processing, automation, and backend services. Knowing how to use the file system module is a key skill.
Progress0 / 4 steps
1
Set up the file system module and read the file
Write import fs from 'fs/promises' to import the file system promises API. Then create an async function called countWords that reads the file input.txt using await fs.readFile('input.txt', 'utf-8') and stores the content in a variable called text.
Node.js
Need a hint?

Use import fs from 'fs/promises' to get the modern promise-based file system API. Use await fs.readFile inside an async function to read the file content as text.

2
Add a variable to count words
Inside the countWords function, create a variable called words that splits the text by spaces using text.split(' '). Then create a variable called wordCount that stores the length of the words array.
Node.js
Need a hint?

Use text.split(' ') to break the text into words. Then use words.length to count how many words there are.

3
Write the word count to a new file
Still inside the countWords function, use await fs.writeFile('output.txt', `Word count: ${wordCount}`) to write the word count to a file named output.txt.
Node.js
Need a hint?

Use await fs.writeFile to save the word count string to output.txt.

4
Call the function to run the script
After the countWords function, add a line to call countWords() so the script runs when executed.
Node.js
Need a hint?

Simply call countWords() after the function to run the code.