Node.js provides a built-in module called fs (File System) that allows you to work with the file system on your computer. This module enables you to perform various operations such as reading from, writing to, and manipulating files and directories. In this tutorial, we will explore how to use the fs module to interact with the file system.
The fs module in Node.js provides both synchronous and asynchronous methods for interacting with the file system. Asynchronous methods are generally preferred because they prevent blocking the main thread of execution, which is crucial for maintaining high performance in server-side applications.
Asynchronous Methods: These methods take a callback function as their last argument. They perform operations asynchronously and call the callback function when the operation completes.
fs.readFile(path[, options], callback)fs.writeFile(file, data[, options], callback)fs.appendFile(file, data[, options], callback)fs.unlink(path, callback)Synchronous Methods: These methods perform operations synchronously and block the execution until the operation completes. They are useful for simple scripts or when you need to ensure that an operation is completed before proceeding.
fs.readFileSync(path[, options])fs.writeFileSync(file, data[, options])fs.appendFileSync(file, data[, options])fs.unlinkSync(path)To read the contents of a file asynchronously, you can use the fs.readFile method. This method takes the path to the file and a callback function that will be executed once the file is read.
1const fs = require('fs');23fs.readFile('example.txt', 'utf8', (err, data) => {4if (err) {5console.error('Error reading file:', err);6return;7}8console.log('File content:', data);9});
If you prefer to use synchronous methods, you can use fs.readFileSync. This method will block the execution until the file is read.
1const fs = require('fs');23try {4const data = fs.readFileSync('example.txt', 'utf8');5console.log('File content:', data);6} catch (err) {7console.error('Error reading file:', err);8}
To write data to a file asynchronously, you can use the fs.writeFile method. This method takes the path to the file, the data to be written, and a callback function.
1const fs = require('fs');23const content = 'Hello, world!';45fs.writeFile('example.txt', content, (err) => {6if (err) {7console.error('Error writing file:', err);8return;9}10console.log('File written successfully');11});
For synchronous writing, you can use fs.writeFileSync.
1const fs = require('fs');23const content = 'Hello, world!';45try {6fs.writeFileSync('example.txt', content);7console.log('File written successfully');8} catch (err) {9console.error('Error writing file:', err);10}
To append data to an existing file asynchronously, you can use the fs.appendFile method. This method takes the path to the file, the data to be appended, and a callback function.
1const fs = require('fs');23const content = ' Appended text!';45fs.appendFile('example.txt', content, (err) => {6if (err) {7console.error('Error appending to file:', err);8return;9}10console.log('Data appended successfully');11});
For synchronous appending, you can use fs.appendFileSync.
1const fs = require('fs');23const content = ' Appended text!';45try {6fs.appendFileSync('example.txt', content);7console.log('Data appended successfully');8} catch (err) {9console.error('Error appending to file:', err);10}
To delete a file asynchronously, you can use the fs.unlink method. This method takes the path to the file and a callback function.
1const fs = require('fs');23fs.unlink('example.txt', (err) => {4if (err) {5console.error('Error deleting file:', err);6return;7}8console.log('File deleted successfully');9});
For synchronous deletion, you can use fs.unlinkSync.
1const fs = require('fs');23try {4fs.unlinkSync('example.txt');5console.log('File deleted successfully');6} catch (err) {7console.error('Error deleting file:', err);8}
After mastering the basics of working with files in Node.js, you can explore more advanced topics such as handling directories, using streams for large files, and integrating with other modules. In the next section, we will dive into the HTTP module to learn how to create a simple web server.
Stay tuned!