Programming

Writing Files In Nodejs? Here Is What You Need To Know

Share

NodeJs file system module will allow us to do file operations create, read, write, update, delete, rename. In this blog, we will use the fs module to perform file operations. In the fs module, every method has asynchronous as well as synchronous forms. Asynchronous methods take the first parameter of the callback function as error and the last parameter as the completion function callback. It’s better to go with the asynchronous method instead of the synchronous method.

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

Step 3: Install the fs module by the following command

$ npm install fs

After installing the fs module and make your nodejs server run. It will run on port 3000. Please find below code.

const fs = require(‘fs’);

const bodyParser = require(‘body-parser’);

const session = require(‘express-session’);

const cors = require(‘cors’);

const app = express();

app.use(bodyParser.json());

app.use(session({

secret : ‘thesecret’,

saveUninitialized: false,

resave : false

}));

router = express.Router({

mergeParams: true

}), router.use(cors());

const startServer = async () => {

const port = process.env.SERVER_PORT || 3000;

await promisify(app.listen).bind(app)(port);

console.log(`Listening on port ${port}`);

}

startServer();

module.exports = router;

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 a 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.

Recent Posts

Optimize Your Hormonal Balance: Enclomiphene Citrate for Enhanced Wellness

Hormonal balance plays a pivotal role in overall well-being, influencing various aspects of health, from…

6 hours ago

Paul Kanes Explores the World of Canine Companionship through Dog Walking

Dog walking is an excellent way to maintain your furry friend's camaraderie and provides many…

8 hours ago

Top 5 Must-Have Features Every Mobile App Needs to Succeed

Introduction Businesses understand the diverse requirements of mobile applications, which provide a competitive advantage. There…

13 hours ago

IoT Data Analytics: Ways to Gain Value from IoT Data

The Internet of Things (IoT) has recently changed the world. It links gadgets together and…

13 hours ago

The Rise of NFTs: Exploring the Impact of Non-Fungible Tokens on the Digital Economy

NFTs, or Non-Fungible Tokens, are revolutionizing the digital economy. These unique digital assets, authenticated through…

1 day ago

What to Ask Before You Hand Your Laptop For Repairing

It is safe to say that if you are in need of a good laptop…

1 day ago