In Node.js, the built-in fs module is used for handling file read and write operations. This module provides various methods for file operations such as creating, reading, writing, deleting, and more. Below, I will explain how to write files using Node.js with examples.
Step 1: Importing the fs module
First, you need to import the fs module into your Node.js script.
javascriptconst fs = require('fs');
Step 2: Using the writeFile method to write files
The fs module provides the writeFile method for writing files. If the file does not exist, this method creates a new file. Using this method requires three parameters: the filename, the content to write, and a callback function to handle the result after writing.
javascriptfs.writeFile('example.txt', 'Hello, world!', (err) => { if (err) throw err; console.log('The file has been saved!'); });
In this example, we attempt to write the string 'Hello, world!' to the example.txt file. If the write is successful, it outputs 'The file has been saved!'.
Step 3: Using the writeFileSync method for synchronous file writing
If you prefer not to handle asynchronous code, the fs module also provides a synchronous version of the write method, writeFileSync.
javascripttry { fs.writeFileSync('example.txt', 'Hello, world!'); console.log('The file has been saved!'); } catch (err) { console.error(err); }
This method blocks the program's execution until the file is written, which is useful in scenarios requiring synchronous processing.
Usage Scenario Example Suppose you are developing an application that needs to log user activities. You can use the above methods to write each user's actions to a log file for subsequent analysis and monitoring.
javascriptconst logActivity = (user, action) => { const logMessage = `${new Date().toISOString()} - ${user}: ${action}\n`; fs.appendFile('activity.log', logMessage, (err) => { if (err) throw err; console.log('Activity has been logged!'); }); }; logActivity('JohnDoe', 'Login'); logActivity('JaneDoe', 'Logout');
In this example, we use the appendFile method, which is similar to writeFile, but appends new content to the end of the file instead of overwriting existing content if the file already exists. This is very useful for log files.
This covers the basic methods for writing files with Node.js. You can choose the appropriate methods and implementation strategies based on your specific requirements.