0
0
Node.jsframework~15 mins

Appending to files in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Appending Text to a File in Node.js
📖 Scenario: You are building a simple Node.js script to keep a log of user actions. Each time a user performs an action, you want to add a new line to a log file without deleting the old entries.
🎯 Goal: Create a Node.js script that appends a new log entry to an existing file called userlog.txt. If the file does not exist, it should be created automatically.
📋 What You'll Learn
Use the built-in fs module to work with files
Create a variable called logEntry with the exact string 'User logged in\n'
Create a variable called filename with the exact string 'userlog.txt'
Use fs.appendFile to add logEntry to filename
Handle errors by logging 'Error writing to file' if any occur
💡 Why This Matters
🌍 Real World
Appending to log files is common in real applications to keep track of user actions, errors, or system events without losing previous data.
💼 Career
Understanding how to work with files and handle asynchronous operations in Node.js is essential for backend development and building reliable server-side applications.
Progress0 / 4 steps
1
Set up the log entry text
Create a variable called logEntry and set it to the string 'User logged in\n' exactly.
Node.js
Need a hint?

Use const to declare logEntry and include the newline character \n at the end.

2
Set the filename variable
Create a variable called filename and set it to the string 'userlog.txt' exactly.
Node.js
Need a hint?

Use const to declare filename with the exact string.

3
Import the fs module
Add a line at the top to import the built-in fs module using import fs from 'fs';.
Node.js
Need a hint?

Use ES module syntax to import fs.

4
Append the log entry to the file
Use fs.appendFile to add logEntry to filename. Provide a callback that logs 'Error writing to file' if an error occurs.
Node.js
Need a hint?

Use fs.appendFile(filename, logEntry, callback) and check if err is truthy inside the callback.