NodeJS Program to Process Exit Codes with Explanation
NodeJS
Easy
Node Basics & Modules
35 views
1 min read
86 words
This problem helps you practice core NodeJS fundamentals in a practical way. It builds intuition around process, exit, code. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Exit with code 1 when an input number is negative.
Input Format
stdin: one integer.
Output Format
Print OK or ERROR.
Constraints
Use process.exitCode instead of process.exit.
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();
if (!s) process.exit(0);
const n = Number(s);
if (n < 0) {
console.log('ERROR');
process.exitCode = 1;
} else {
console.log('OK');
}
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
Exit with code 1 when an input number is negative.
Input / Output
Input
stdin: one integer.
Output
Print OK or ERROR.
Constraints
Use process.exitCode instead of process.exit.
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();
if (!s) process.exit(0);
const n = Number(s);
if (n < 0) {
console.log('ERROR');
process.exitCode = 1;
} else {
console.log('OK');
}
Solutions (0)
No solutions submitted yet. Be the first!