NodeJS Program to Read From Stdin Lines with Explanation
NodeJS
Easy
CLI Tools & Debugging
35 views
1 min read
83 words
This problem helps you practice core NodeJS fundamentals in a practical way. It builds intuition around stdin, read, line. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Read all stdin, split into lines, and print count.
Input Format
stdin: any text.
Output Format
Print integer.
Constraints
Trim ending newline correctly.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
const fs = require('fs');
const text = fs.readFileSync(0, 'utf8');
if (!text) process.exit(0);
const lines = text.replace(/\
/g, '').split('\
');
if (lines.length && lines[lines.length - 1] === '') lines.pop();
console.log(lines.length);
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
Read all stdin, split into lines, and print count.
Input / Output
Constraints
Trim ending newline correctly.
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 text = fs.readFileSync(0, 'utf8');
if (!text) process.exit(0);
const lines = text.replace(/\
/g, '').split('\
');
if (lines.length && lines[lines.length - 1] === '') lines.pop();
console.log(lines.length);
Solutions (0)
No solutions submitted yet. Be the first!