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.
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
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
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"
},
...
...
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.')
}
})
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.
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.
In this quick tutorial, we will show you how to quite easily add the active…
In this tutorial, we will learn how to create a Redux Store in React application.…
This detailed guide will cover how to create the Load More button and display data…
In this tutorial, we will step by step learn how to configure redux persist in…
In this comprehensive tutorial, we will learn how to persist redux store's states in React…
In this guide, we are going to learn how to add dark mode and light…