In this tutorial, we're going to explore how to perform file and directory operations in Node.js. You will learn how to create, read, update, and delete files and directories using the built-in fs
(file system) module in Node.js.
By the end of this tutorial, you should be able to:
Prerequisites: Basic knowledge of JavaScript and Node.js is required. You should also have Node.js installed on your system.
Node.js fs
module provides an API to interact with the file system in a manner closely modeled around standard POSIX functions.
To use this module, you need to require it in your script:
const fs = require('fs');
To create a new file in Node.js, you can use the fs.writeFile()
method:
fs.writeFile('test.txt', 'Hello, World!', (err) => {
if (err) throw err;
console.log('File has been created');
});
To read a file in Node.js, you can use the fs.readFile()
method:
fs.readFile('test.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
Let's put everything together and create a more complex example:
// Include fs module
const fs = require('fs');
// Use fs.writeFile() method to create a new file
fs.writeFile('test.txt', 'Hello, World!', (err) => {
if (err) throw err;
console.log('File has been created');
// Use fs.readFile() method to read the file
fs.readFile('test.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
});
In this code snippet:
fs
module.fs.writeFile()
to create a new file 'test.txt' and write 'Hello, World!' to it. If the file already exists, it will be overwritten.fs.writeFile()
, we use fs.readFile()
to read the file we just created. The content of the file will be printed to the console.In this tutorial, we've covered the basics of performing file and directory operations in Node.js. We've learned how to create a new file and how to read a file using the fs
module. The next step would be to explore other methods provided by the fs
module, such as fs.appendFile()
, fs.unlink()
, and fs.mkdir()
.
Exercise 1 Solution:
fs.appendFile('test.txt', ' This is a test.', (err) => {
if (err) throw err;
console.log('Text has been appended');
});
Exercise 2 Solution:
fs.unlink('test.txt', (err) => {
if (err) throw err;
console.log('File has been deleted');
});
Exercise 3 Solution:
fs.mkdir('testDir', (err) => {
if (err) throw err;
console.log('Directory has been created');
});