Hello Developers,
In this tutorial, I will show you how to deal with the NodeJs fs.exists()
module asynchronously 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.exists()
module.
The package.json file will be like the below:
/package.json
{
"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.exists()
the method we have to give the file name with the function. We have written some code to get the response of whether the file exists or not. The source code is given below:
/index.js
var fs = require('fs');
var http = require('http');
var server = http.createServer(function (req, res) {
if (req.url == "/") {
fs.existsSync('demo.txt', function (exists) {
if (exists) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('File Exists');
res.end();
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('File Does not Exists');
res.end();
}
});
}
});
server.listen(5000);
console.log('Server running Successfully');
Now run npm start in the terminal.
npm start
We will get a message "File Exists" if the demo.txt exists in the directory.
Hope this might help you in the development journey.
Read More: Working with NodeJs fs.existsSync() function using synchronous way