NodeJS Program to Stream Copy File with Explanation
NodeJS
Hard
Streams & Buffers
30 views
1 min read
84 words
This problem helps you practice core NodeJS fundamentals in a practical way. It builds intuition around done, stream, copy. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Copy a file using streams and print DONE.
Input Format
stdin: src dest.
Output Format
Print DONE or FAIL.
Constraints
Use createReadStream and createWriteStream.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
const fs = require('fs');
const parts = fs.readFileSync(0, 'utf8').trim().split(/\\s+/);
if (parts.length < 2) process.exit(0);
const src = parts[0];
const dest = parts[1];
const r = fs.createReadStream(src);
const w = fs.createWriteStream(dest);
r.on('error', () => console.log('FAIL'));
w.on('error', () => console.log('FAIL'));
w.on('close', () => console.log('DONE'));
r.pipe(w);
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 file using streams and print DONE.
Input / Output
Output
Print DONE or FAIL.
Constraints
Use createReadStream and createWriteStream.
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 parts = fs.readFileSync(0, 'utf8').trim().split(/\\s+/);
if (parts.length < 2) process.exit(0);
const src = parts[0];
const dest = parts[1];
const r = fs.createReadStream(src);
const w = fs.createWriteStream(dest);
r.on('error', () => console.log('FAIL'));
w.on('error', () => console.log('FAIL'));
w.on('close', () => console.log('DONE'));
r.pipe(w);
Solutions (0)
No solutions submitted yet. Be the first!