Check if a file exists in Node.js using fs (File System) module

Check if a file exists in Node.js using fs (File System) module

The fs module provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions. It provides a lot of very useful functionality to access and interact with the file system. There is no need to install it because it is a part of the Node.js core. The fs module is responsible for all the asynchronous or synchronous file I/O operations.

To check if a file exists in Node.js we will use the eexistsSync method of the fs module. In the following example we create a simple server in order to test our app. So after getting a request we call the exists method and return either the file exists or not.

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

const port = process.env.PORT || "3100";

const server = http.createServer(function (req, res) {
  // Set content type
  res.writeHead(200, {"Content-Type": "text/html"});

  // Check for file existance
  if(fs.existsSync('file.ext')){
    res.write("The file exists")
  }else{
    res.write("The file does not exists")
  }

  // End the response
  res.end();

}).listen(port);