JavaScript · Syntax · Beginner

Working with files: reading and writing

10 tasks

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.

Reading files with Node.js fs

#
In Node.js, file access is provided by the built-in fs module. Import it at the top of your script: ```javascript const fs = require("fs"); ``` Reading a file synchronously — readFileSync returns the entire content as a string: ```javascript const content = fs.readFileSync("note.txt", "utf-8"); console.log(content); ``` The second argument is the encoding. Without it, readFileSync returns a Buffer object, not a string. Sync vs async: readFileSync blocks execution until the file is loaded. For scripts and exercises this is fine. In production servers you would use the async version (fs.promises.readFile) to avoid blocking the event loop. Reading line by line — split on the newline character: ```javascript const content = fs.readFileSync("tasks.txt", "utf-8"); const lines = content.split("\n"); console.log(lines.length); // number of lines for (const line of lines) { console.log(line.trim()); // trim() removes trailing whitespace and \r on Windows } ``` If the file ends with a newline (which is standard), the last element of lines will be an empty string. Filter it out with lines.filter(l => l.length > 0) if needed. Checking whether a file exists before reading: ```javascript if (fs.existsSync("data.txt")) { const content = fs.readFileSync("data.txt", "utf-8"); } ```

Writing and appending

#
Writing to a file uses writeFileSync. If the file does not exist, Node creates it. If it already exists, writeFileSync overwrites it completely. ```javascript fs.writeFileSync("message.txt", "Hello, file!"); ``` You can optionally pass the encoding as a third argument — it defaults to utf-8 when writing strings, so it is usually not needed. Writing multiple lines — join an array with newline characters: ```javascript const products = ["bread", "milk", "cheese"]; fs.writeFileSync("shopping.txt", products.join("\n")); ``` Appending with appendFileSync adds to the end of the file without erasing existing content: ```javascript fs.appendFileSync("log.txt", "New entry\n"); ``` Use appendFileSync for logs, writeFileSync for files you regenerate from scratch each time. The difference matters: using writeFileSync on a log file discards all previous entries. To read a file, modify the content, and write it back: ```javascript let content = fs.readFileSync("text.txt", "utf-8"); content = content.toUpperCase(); fs.writeFileSync("text.txt", content); ``` Two separate operations — read, then write. There is no mode that combines both safely.

File processing patterns

#
Creating a file with initial content and reading it back — many exercises follow this two-step shape: ```javascript fs.writeFileSync("words.txt", "code javascript file student"); const content = fs.readFileSync("words.txt", "utf-8"); const words = content.split(" "); const longest = words.reduce((a, b) => a.length >= b.length ? a : b); console.log(longest); ``` reduce() with a comparison callback finds the longest word without writing a separate loop. The accumulator starts as the first element. Filtering lines and writing them to a new file: ```javascript const lines = fs.readFileSync("emails.txt", "utf-8").split("\n"); const valid = lines.filter(line => line.includes("@")); fs.writeFileSync("valid_emails.txt", valid.join("\n")); ``` Chaining readFileSync, split, and filter into one expression keeps things concise when you do not need the intermediate values later. Writing a computed report: ```javascript const content = fs.readFileSync("article.txt", "utf-8"); const wordCount = content.split(/\s+/).filter(w => w.length > 0).length; fs.writeFileSync("report.txt", `Word count: ${wordCount}\n`); ``` Template literals handle the conversion from number to string automatically. Concatenating with + also works, but template literals read more cleanly when mixing text and values.
01

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"));
02

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);
03

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);
04

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);
05

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);
06

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);
07

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);
08

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);
09

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);
10

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);