Node.js
Move & Copy Files in Node.js
How to move, copy, and rename files in Node.js using the built-in fs module with both callback and promise-based APIs.
File Operations in Node.js
Node.js provides the built-in fs module for file system operations. This tutorial covers copying, moving, and renaming files using both the callback API and the modern fs/promises API.
Copy a File
Use fs.copyFile() (Node 8.5+) to copy a file to a new location:
const fs = require('fs'); // Callback API fs.copyFile('source.txt', 'dest.txt', (err) => { if (err) throw err; console.log('File copied successfully'); }); // Promise API (Node 10+) const fsPromises = require('fs/promises'); async function copyFile() { await fsPromises.copyFile('source.txt', 'dest.txt'); console.log('File copied'); }
Move / Rename a File
Use fs.rename() to move or rename a file. This works across directories on the same filesystem:
// Rename in the same directory fs.rename('old-name.txt', 'new-name.txt', (err) => { if (err) throw err; console.log('File renamed'); }); // Move to another directory fs.rename('./uploads/file.txt', './archive/file.txt', (err) => { if (err) throw err; console.log('File moved'); });
Cross-Device Move (Copy + Delete)
fs.rename() fails across different filesystems or drives. For a cross-device move, copy first then delete the original:
const fsPromises = require('fs/promises'); async function moveFile(src, dest) { try { // Try rename first (fast, same-device) await fsPromises.rename(src, dest); } catch (err) { if (err.code === 'EXDEV') { // Cross-device: copy then delete await fsPromises.copyFile(src, dest); await fsPromises.unlink(src); } else { throw err; } } } moveFile('/mnt/usb/data.csv', './local/data.csv');
Copy a Directory Recursively
Node 16.7+ supports recursive directory copying with fs.cp():
const fsPromises = require('fs/promises'); // Copy entire directory (Node 16.7+) await fsPromises.cp('./src', './backup', { recursive: true }); // For older Node versions, use a manual walk async function copyDir(src, dest) { await fsPromises.mkdir(dest, { recursive: true }); const entries = await fsPromises.readdir(src, { withFileTypes: true }); for (const entry of entries) { const srcPath = `${src}/${entry.name}`; const destPath = `${dest}/${entry.name}`; if (entry.isDirectory()) { await copyDir(srcPath, destPath); } else { await fsPromises.copyFile(srcPath, destPath); } } }
Last updated: 2026 • Browse all courses