Node Js Copy File to New Directory with FS Module Tutorial

Last Updated on by in Node JS

A large portion of developers’ time goes into managing files and folders. What if we reduce the pain of moving files from one location to another programmatically.

This quick tutorial will show you how to copy files in node js from one folder to another using node’s very own fs module.

The term fs stands for file system; it lets you work with the file system on your computer. Using the fs module in node is pretty simple.

Generally, the file system module helps you read files, create files, update files, delete files, rename files, and tons of other methods which will allow managing files of your node project.

How to Copy File from One Folder to Another in Node

  • Step 1: Make New Directory
  • Step 2: Create Package JSON
  • Step 3: Register Script
  • Step 4: Build Script with FS Module
  • Step 5: Test Node Feature

Create Node Folder

First, lets start with setting up the stage, here is the command which will create a folder on your system.

mkdir node-fs

Move into the folder using the suggested command.

cd node-fs

Create Package JSON

Package file is the most quintessential file in node based projects. Whys so? because it allows keeping the important information at one place.

The significant data that we are talking about are scripts, project detail, modules with version number etc.

npm init

Register Script

In order to write the coding logic, we need a file we will call it script file. Go ahead and create an app.js file in your node folder.

This file has to be added into the scripts property of package.json file, here is the instruction to register this file.

...
...
"scripts": {
    "start": "node app.js"
  },
...
...

Build Script with FS Module

In order to relocate the file within node directory requires two folders, so create ‘img’ folder and keep an image inside of it. Secondly, create the ‘resources’ folder where this file has to be copied,

Then, open the app.js file, inside this file you have to append the following code like given below.

const fs = require('fs')

const filePath = './img/samurai.jpg'
const copy = './resources/samurai.jpg'

fs.copyFile(filePath, copy, (error) => {
  if (error) {
    throw error
  } else {
    console.log('File has been moved to another folder.')
  }
})

Test Node Feature

Let’s see how does the image relocation in node is done. Make sure to execute the following command from the command prompt of your terminal.

npm start

You will see after executing above command file moved from img folder to resources folder.

Node Js Copy File to New Directory with FS Module Tutorial

Conclusion

This guide was an attempt to copy files to another directory in node js. We have shared the fastest way to copy a file using the fs module in the node.

We utterly looked at the asynchronous method copyFile method that we accessed through the fs module of the node.