Create and Read a file in Node.js using fs (File System) module

Read and Create a file 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.

Read a file in Node.js using fs (File System) module

To read a file in Node.js we will use the readFile method of the fs module. It supports both synchronous and asynchronous methods. In the following example we create a simple server in order to test our app. So after getting a request we call the readFile method and return either the file is copied or not.

1 Asynchronous usage of readFile in Node.js

const http = require("http");
const 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"});

  fs.readFile('file.html', (err, data) => {
    if (err){
          // Handle the error
          if(err.code=='ENOENT'){
            res.write("File not found")
          }else if('EISDIR'){
            res.write("Illegal operation on a directory")
          }else{
            res.write("An error occured")
          }
        }else{
          // File successfully readed
          res.write(data);
      }
      // End the response
      res.end();
    });

}).listen(port);

2 Synchronous usage of readFile in Node.js

const http = require("http");
const 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"});
  try {
      // File created successfully
      let data = fs.readFileSync("file - Copie3.html");
      res.write(data);
    } catch (err) {
        // Handle the error
        if(err.code=='ENOENT'){
          res.write("File not found")
        }else if('EISDIR'){
            res.write("Illegal operation on a directory")
        }else{
          res.write("An error occured")
        }
      }
    // End the response
    res.end();

}).listen(port);

Write a file in Node.js using fs (File System) module

To create a file in Node.js we will use the writeFile method of the fs module. It supports both synchronous and asynchronous methods. In the following example we create a simple server in order to test our app. So after getting a request we call the writeFile method and return either the file is copied or not.

1 Asynchronous usage of writeFile in Node.js

const http = require("http");
const 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"});

  let content = "<p>YamiCode</p>"
  fs.writeFile('file.html', content, (err) => {
    if (err){
          // Handle the error
          res.write("An error occured")
      }else{
          // File created successfully
          res.write("file created successfully");
      }
      // End the response
      res.end();
    });

}).listen(port);

2 Synchronous usage of writeFile in Node.js

const http = require("http");
const 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"});
    try {
      let data = "<p>YamiCode</p>";
      // Create file successfully
      fs.writeFileSync("file.html", data);

      // File created successfully
      res.write("File created successfully");
    } catch (err) {
          res.write("An error occured");
    }
    // End the response
    res.end();

}).listen(port);