Science and Technology

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

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

Let CronJ Assist you, which is a top Node Js Development Company.

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

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!…

Looking for Mobile App development company | Software Development Company?

Tags
Show More

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Articles

Back to top button
Close
Close