Working with NodeJs fs.writeFile() function using asynchronous way

Working with NodeJs fs.writeFile() function using asynchronous way

K. M. Shawkat Zamil | September 27, 2022

Hello Developers,

In this tutorial, I will show you how to deal with the NodeJs fs.writeFile() module asynchronous way. First, you need to create a server using the HTTP module. (NodeJs Server Related Tutorial)

If you are new at NodeJs development, this demonstration is for you. First, you need to initialize the node using the below command in a directory:


npm init --y


Then package.json will be created in the directory. Now we need to create the index.js file and an HTML file to use the fs.writeFile() module.

The package.json file will be like the below:



  "name": "fsmodule",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  "keywords": [],
  "author": "",
  "license": "ISC"


 In our index.js file, first, we created a server and we have to call the fs module to work with File System. After that, we called fs.writeFile() the method and give a file name and file content with a callback function. In the callback function, we have written some code to get the response of whether the file was created or not. The source code is given below:



var fs = require('fs');
var http = require('http');

var server = http.createServer(function (req, res) { 
    if (req.url = "/") { 
        fs.writeFile('demo.txt', 'hello World', function (error) {
            if (error) {
                res.writeHead(200, { 'Content-Type': 'text/html' });
                res.write('File Write Failed');
            } else { 
                res.writeHead(200, { 'Content-Type': 'text/html' });
                res.write('File Write Success');

console.log('Server running Successfully');


Now run npm start in the terminal.


npm start


We have created the file using the code. If you get any error then you will find it in the browser.



Hope this might help you in the development journey. 


Read More: Working with NodeJs fs.writeFileSync() function using synchronous way


K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.