JavaScript · Syntax · Beginner
Working with files: reading and writing
Hands-on exercises for working with files in JavaScript on Node.js: reading text, writing lines, appending data, counting lines and words, processing file contents, and creating simple reports using the fs module.
Quick topic start and explanations before exercises (exercises below):
Writing and appending
#File processing patterns
#Exercises:
Read the whole file.
#Create a file note.txt with the text "JavaScript files". Then read the entire contents of the file using the fs module and print it to the console.
const fs = require("fs");
const fileName = "note.txt";
Solution
const fs = require("fs");
const fileName = "note.txt";
fs.writeFileSync(fileName, "JavaScript files", "utf8");
const text = fs.readFileSync(fileName, "utf8");
console.log(text);
// or like this: read the file directly inside console.log
const fs = require("fs");
const fileName = "note.txt";
fs.writeFileSync(fileName, "JavaScript files", "utf8");
console.log(fs.readFileSync(fileName, "utf8"));
Write a string to a file.
#The variable text stores a message. Write this message to the file message.txt, then read the file and print its contents.
const fs = require("fs");
const text = "Message for file";
const fileName = "message.txt";
Solution
const fs = require("fs");
const text = "Message for file";
const fileName = "message.txt";
fs.writeFileSync(fileName, text, "utf8");
const result = fs.readFileSync(fileName, "utf8");
console.log(result);
Add a line to the end of a file.
#The file log.txt already contains the line "Start". The variable newLine stores a new line. Add it to the end of the file on a new line and print the final contents of the file.
const fs = require("fs");
const fileName = "log.txt";
fs.writeFileSync(fileName, "Start", "utf8");
const newLine = "Next step";
Solution
const fs = require("fs");
const fileName = "log.txt";
fs.writeFileSync(fileName, "Start", "utf8");
const newLine = "Next step";
fs.appendFileSync(fileName, "\n" + newLine, "utf8");
const text = fs.readFileSync(fileName, "utf8");
console.log(text);
Count lines in a file.
#Create a file tasks.txt with three lines: "Learn", "Practice", "Repeat". Read the file and print the number of lines.
const fs = require("fs");
const fileName = "tasks.txt";
Solution
const fs = require("fs");
const fileName = "tasks.txt";
fs.writeFileSync(fileName, "Learn\nPractice\nRepeat", "utf8");
const text = fs.readFileSync(fileName, "utf8");
const lines = text.split("\n");
console.log("Line count:", lines.length);
Find the longest word.
#Create a file words.txt with words separated by spaces: "code javascript file student". Read the file and print the longest word.
const fs = require("fs");
const fileName = "words.txt";
Solution
const fs = require("fs");
const fileName = "words.txt";
fs.writeFileSync(fileName, "code javascript file student", "utf8");
const text = fs.readFileSync(fileName, "utf8");
const words = text.split(" ");
let longest = words[0];
for (const word of words) {
if (word.length > longest.length) {
longest = word;
}
}
console.log(longest);
Write a shopping list.
#There is a shopping array: ["bread", "milk", "cheese"]. Write each array element to the file shopping.txt on a new line. Then read the file and print its contents.
const fs = require("fs");
const products = ["bread", "milk", "cheese"];
const fileName = "shopping.txt";
Solution
const fs = require("fs");
const products = ["bread", "milk", "cheese"];
const fileName = "shopping.txt";
const text = products.join("\n");
fs.writeFileSync(fileName, text, "utf8");
const result = fs.readFileSync(fileName, "utf8");
console.log(result);
Sum of numbers from a file.
#Create a file numbers.txt where numbers are written separated by spaces: 5 10 15 20. Read the file, calculate the sum of the numbers, and print the result.
const fs = require("fs");
const fileName = "numbers.txt";
Solution
const fs = require("fs");
const fileName = "numbers.txt";
fs.writeFileSync(fileName, "5 10 15 20", "utf8");
const text = fs.readFileSync(fileName, "utf8");
const numbers = text.split(" ");
let total = 0;
for (const number of numbers) {
total += Number(number);
}
console.log("Sum:", total);
Filter lines by symbol.
#Create a file emails.txt with several lines, some of which contain the @ symbol. Read the file and write only the lines with @ into a new file valid_emails.txt. Then print the contents of the new file.
const fs = require("fs");
const fileName = "emails.txt";
const resultFile = "valid_emails.txt";
Solution
const fs = require("fs");
const fileName = "emails.txt";
const resultFile = "valid_emails.txt";
fs.writeFileSync(fileName, "[email protected]\nhello\[email protected]\ntest", "utf8");
const text = fs.readFileSync(fileName, "utf8");
const lines = text.split("\n");
const validLines = [];
for (const line of lines) {
if (line.includes("@")) {
validLines.push(line);
}
}
fs.writeFileSync(resultFile, validLines.join("\n"), "utf8");
const result = fs.readFileSync(resultFile, "utf8");
console.log(result);
Rewrite a file in uppercase.
#Create a file text.txt with the line "hello file". Read the contents, convert them to uppercase, and rewrite the same file with the new text. Then print the final contents.
const fs = require("fs");
const fileName = "text.txt";
Solution
const fs = require("fs");
const fileName = "text.txt";
fs.writeFileSync(fileName, "hello file", "utf8");
let text = fs.readFileSync(fileName, "utf8");
text = text.toUpperCase();
fs.writeFileSync(fileName, text, "utf8");
const result = fs.readFileSync(fileName, "utf8");
console.log(result);
Report with word count.
#Create a file article.txt with several words. Read the file, count the number of words, and write a line like "Word count: N" into the file report.txt. Then print the contents of report.txt.
const fs = require("fs");
const articleFile = "article.txt";
const reportFile = "report.txt";
Solution
const fs = require("fs");
const articleFile = "article.txt";
const reportFile = "report.txt";
fs.writeFileSync(articleFile, "JavaScript helps practice file reading and writing", "utf8");
const text = fs.readFileSync(articleFile, "utf8");
const words = text.trim().split(/\s+/);
const count = words.length;
fs.writeFileSync(reportFile, `Word count: ${count}`, "utf8");
const result = fs.readFileSync(reportFile, "utf8");
console.log(result);