Now let’s move on to Nodejs file examples
Step 1: Create a directory for our application.
$ mkdir nodeFileOperations
$ cd nodeFileOperations
Step 2: Now generate package.json. Run the following command. So that all the dependencies can be listed.
$ npm init
Important flags:
r: Open file for reading, the exception will come when a file does not exist.
r+: Open file for reading and writing, the exception will come when the file does not exist.
rs: Open file for reading in the mode of synchronous.
rs+: Open file for reading and writing, asking the OS to open the file in the mode of synchronous.
w: Open file for writing. The file will create if not exist or truncate if exist.
wx: Open file for writing like ‘w’ but fails if the path exists.
w+: Open file for reading and writing, the file is created if it does not exist or truncated if exists.
wx+: Open file for read and write like ‘w+’ but fails if the path exists.
a: Open file for appending, the file will create if it does not exists.
ax: Open file for appending like ‘a’ but fails if the path exists.
a+: Open file for reading and appending and the file is created if it does not exist.
ax+: Open file for reading and appending like ‘a+’ but fails if the path exists.
Open a file:
To open a file in asynchronous mode use below syntax.
fs.open(path, flags[, mode], callback)
Parameters:
Path: This is a string should have file name along with the path.
Flags: Flags indicate the behavior of the file to be opened. All possible flags are mentioned above.
Mode: It sets the file mode, but only the file was created, it defaults to readable and writable.
Callback: Its a callback function which gets two arguments.
console.log("Going to open file!");
fs.open('input.txt', 'r+', (err, fd) => {
if (err) {
return console.error(err);
}
console.log("File opened successfully!..");
});
Output:
Going to open file
Listening on port 3000
File opened successfully!…
Create Files:
To create new files fs module has the following methods:
fs.appendFile()
fs.open()
fs.writeFile()
The fs.appendFile() method appends specific content to the file. If the file does not exist, then the file will create.
const fs = require('fs');
fs.appendFile('input.txt', 'Hello content!', (err) => {
if (err) throw err;
console.log('Content Saved!..');
});
Output:
Listening on port 3000
console.log(‘Content Saved!..’);
fs.writeFile() method replaces the specified file and content if it exists. If the file does not exist, a new file containing the given content will be created.
const fs = require('fs');
fs.writeFile('input.txt', 'Hello Write file content!', (err) => {
if (err) throw err;
console.log('Write file content saved!...');
});
Output:
Listening on port 3000
Write file content saved!…
Update Files:
The fs module has the following methods for updating.
fs.appendFile(): This method appends the given content at the end of the specified file.
fs.writeFile(): This method replaces the given file and content.
Delete Files:
fs.unlink() method will use to delete a file by using fs module.
const fs = require('fs');
fs.unlink('input.txt', (err) => {
if (err) throw err;
console.log('File deleted!..');
});
Output:
Listening on port 3000
File deleted!…
Rename Files:
fs.rename() method will be used to rename a specified file.
const fs = require('fs');
fs.rename('input.txt', 'input_renamed.txt' (err) => {
if (err) throw err;
console.log('File Renamed!..');
});
Create a Directory:
fs.mkdir() method is used to make a directory:
const fs = require('fs');
fs.mkdir('/tmp/home/test', (err) => {
if (err) throw err;
console.log("Directory created successfully!..");
});
Output:
Listening port 3000
Directory created successfully!…
Read a Directory:
fs.readdir() method is used to read a directory.
const fs = require('fs');
fs.readdir("/tmp/home/nodeFileOperations/", (err, files) => {
if (err) throw err;
files.forEach((file) => {
console.log(file);
});
});
Output:
Listening on port 3000
index.js
index_1.js
input.txt
node_modules
package-lock.json
Package.json
Remove a Directory:
fs.rmdir() method is used to remove a directory
const fs = require('fs');
fs.rmdir("/tmp/home/nodeFileOperations/", (err) => {
if (err) throw err;
console.log("Going to read directory /tmp/home/");
fs.readdir("/tmp/home/", (err, files) => {
if (err) throw err;
files.forEach((file) => {
console.log(file);
});
});
});
Useful methods of fs module:
fs.readFile(file_name [,options], callback): This method reads an existing file.
fs.writeFile(file_name, data[, options], callback): This method writes to the file. If a file exists then overwrite the content otherwise it will create a new file.
fs.open(path, flags[, mode], callback): This method open file for reading or writing.
fs.rename(oldPath, newPath, callback): This method will rename an existing file.
fs.chown(path, uid, gid, callback): This will asynchronous chown.
fs.stat(path, callback): This method will return fs.stat object which includes important file statistics.
fs.link(srcpath, dstpath, callback): This method will links a file asynchronously.
fs.symlink(destination, path[, type], callback): This method will do Symlink asynchronously.
fs.rmdir(path, callback): This method will rename an existing directory.
fs.mkdir(path[, mode], callback): This method will create a new directory.
fs.readdir(path, callback): This method will read the content of the specified directory.
fs.utimes(path, atime, mtime, callback): This method changes the timestamp of the file.
fs.exists(path, callback): This method determines whether the specified file exists or not.
fs.access(path[, mode], callback): This method will test a user’s permissions for the specified file.