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

Copy 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.

To copy a file in Node.js we will use the copy 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 copy method and return either the file is copied or not.

1 Asynchronous usage of copy in Node.js

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"});

  // Copy file
  fs.copyFile('old_name.ext', 'copy_name.ext', (err) => {
    if (err){
      // Handle the error
      if(err.code=='ENOENT'){
        res.write("File not found")
      }else{
        res.write("An error occured")
      }
    }else{
      // File successfully copied
      res.write("successfully copied")
    }

    // End the response
    res.end();
  });

}).listen(port);

2 Synchronous usage of copy in Node.js

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"});

  try {

    // Copy file
    fs.copyFileSync('old_name.ext', 'copy_name.ext');
    res.write("successfully copied");

  } catch (err) {

    // Handle the error
    if(err.code=='ENOENT'){
      res.write("File not found");
    }else{
      res.write("An error occured");
    }
    
  }

  // End the response
  res.end();

}).listen(port);