NodeJS Program to Copy File with Explanation
NodeJS
Hard
File System & Paths
23 views
1 min read
85 words
This problem helps you practice core NodeJS fundamentals in a practical way. It builds intuition around copied, copy, file. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Copy a source file to destination and print COPIED.
Input Format
stdin: two paths (src dest).
Output Format
Print COPIED or FAIL.
Constraints
Use readFileSync/writeFileSync.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
const fs = require('fs');
const s = fs.readFileSync(0, 'utf8').trim().split(/\\s+/);
if (s.length < 2) process.exit(0);
const src = s[0];
const dest = s[1];
try {
const buf = fs.readFileSync(src);
fs.writeFileSync(dest, buf);
console.log('COPIED');
} catch (e) {
console.log('FAIL');
}
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Copy a source file to destination and print COPIED.
Input / Output
Input
stdin: two paths (src dest).
Output
Print COPIED or FAIL.
Constraints
Use readFileSync/writeFileSync.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
const fs = require('fs');
const s = fs.readFileSync(0, 'utf8').trim().split(/\\s+/);
if (s.length < 2) process.exit(0);
const src = s[0];
const dest = s[1];
try {
const buf = fs.readFileSync(src);
fs.writeFileSync(dest, buf);
console.log('COPIED');
} catch (e) {
console.log('FAIL');
}
Solutions (0)
No solutions submitted yet. Be the first!