How to Copy File in Node.js: Simple Guide with Examples
In Node.js, you can copy a file using the
fs.copyFile method from the built-in fs module. For asynchronous code with promises, use fs.promises.copyFile to copy files easily and efficiently.Syntax
The basic syntax to copy a file in Node.js uses the fs.copyFile method. It takes three arguments: the source file path, the destination file path, and a callback function that runs after copying.
For promise-based usage, fs.promises.copyFile returns a promise that resolves when the copy is done.
javascript
const fs = require('fs'); // Callback style fs.copyFile('src', 'dest', (err) => { if (err) throw err; console.log('File was copied'); }); // Promise style fs.promises.copyFile('src', 'dest') .then(() => console.log('File was copied')) .catch(err => console.error(err));
Example
This example copies a file named source.txt to destination.txt using the promise-based fs.promises.copyFile. It logs a success message or an error if something goes wrong.
javascript
import { promises as fs } from 'fs'; async function copyFile() { try { await fs.copyFile('source.txt', 'destination.txt'); console.log('File copied successfully'); } catch (error) { console.error('Error copying file:', error); } } copyFile();
Output
File copied successfully
Common Pitfalls
Common mistakes when copying files in Node.js include:
- Not handling errors, which can cause your program to crash silently.
- Using relative paths incorrectly, leading to "file not found" errors.
- Trying to copy a file onto itself, which throws an error.
Always check that source and destination paths are correct and different.
javascript
const fs = require('fs'); // Wrong: copying file onto itself fs.copyFile('file.txt', 'file.txt', (err) => { if (err) console.error('Error:', err.message); }); // Right: different source and destination fs.copyFile('file.txt', 'copy.txt', (err) => { if (err) console.error('Error:', err.message); else console.log('Copied successfully'); });
Quick Reference
Here is a quick summary of the fs.copyFile method options:
| Parameter | Description |
|---|---|
| src | Path to the source file to copy |
| dest | Path where the file should be copied |
| flags (optional) | Optional flags to modify behavior (e.g., fs.constants.COPYFILE_EXCL to fail if dest exists) |
| callback | Function called after copy finishes with error if any |
Key Takeaways
Use fs.copyFile or fs.promises.copyFile to copy files in Node.js easily.
Always handle errors to avoid crashes during file operations.
Ensure source and destination paths are correct and not the same.
Use promise-based fs.promises.copyFile for cleaner async code.
You can add flags like COPYFILE_EXCL to control copy behavior.