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 filesCreate 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 filenameHandle 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