Solve Problems, Don't Fight JavaScript Streams!
In Java, you have a simple Scanner. In JavaScript, online platforms require you to process system streams manually. This guide simplifies everything so you can write JS with the familiarity of standard competitive coding libraries.
The "Scanner" Boilerplate (For Codeforces, AtCoder)
Use this copy-paste boilerplate when the platform feeds input file streams to your code. It works exactly like Java's sc.nextInt() by collecting all system data synchronously on execution start.
const fs = require("fs");
// 1. Read entire input file synchronously from Standard Input (Descriptor 0)
// 2. Remove edge whitespaces and split by any whitespace group (spaces, tabs, newlines)
const tokens = fs.readFileSync(0, "utf-8").trim().split(/\s+/);
let ptr = 0; // The active token pointer
// Behaves exactly like Java's sc.next()
function next() {
return tokens[ptr++];
}
// Behaves exactly like Java's sc.nextInt()
function nextInt() {
return Number(tokens[ptr++]);
}
// Behaves exactly like Java's sc.nextDouble() or parseFloat
function nextFloat() {
return parseFloat(tokens[ptr++]);
}
// ============================================
// YOUR PROBLEM IMPLEMENTATION
// ============================================
function solve() {
if (tokens.length === 0 || tokens[0] === "") return;
const n = nextInt(); // First variable
const k = nextInt(); // Second variable
const arr = [];
for (let i = 0; i < n; i++) {
arr.push(nextInt()); // Appends to array
}
console.log(`Parsed values: N=${n}, K=${k}`);
console.log("Parsed Array:", arr);
}
solve();
Understanding Platform "Driver Code"
Not all platforms ask you to parse raw files. Platforms are generally split into **two layout types**:
Type A: Function Stubs (LeetCode)
You write **zero parsing code**. The platform has its own hidden driver that handles system input and feeds your solution class with pure native parameters.
/**
* LeetCode passes values as arguments
* No require("fs") needed!
*/
class Solution {
solve(n, k, arr) {
// Just implement logic here
return arr.filter(x => x > k).length;
}
}
Type B: HackerRank Driver Code
HackerRank gives you a pre-written main execution loop. It generates lines, trims them, and then maps variables before triggering your solution module.
// HackerRank automatic driver block snippet
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const n = parseInt(readLine().trim(), 10);
const result = solution(n);
ws.write(result + '\n');
ws.end();
}
Converting Strings to Numbers
Unlike Java where variables are typed strictly, JavaScript reads files as raw strings. Converting those tokens into real numbers requires choosing the correct parser:
| Method | Behavior for Integers | Behavior for Decimals | Empty String ("") Value | Crucial Drawback |
|---|---|---|---|---|
| Number(str) | Converts cleanly | Converts cleanly | 0 (DANGEROUS) | Returns NaN if string has letters |
| parseInt(str, 10) | Converts cleanly | Truncates fraction | NaN |
Always supply radix 10 to avoid parsing octal bases |
| +str (Unary +) | Converts cleanly | Converts cleanly | 0 (DANGEROUS) | Can be hard to read when writing equations |
| ~~str (Double NOT) | Ultra-fast conversion | Truncates fraction | 0 | Only works safely within standard 32-bit integer limits |
The Power of Magic JSON Parsing
Sometimes competitive coding problems feed you structured data arrays directly, looking something like this:
[[1,2],[3,4],[5,6]].
Instead of spending hours writing nested loops and string splitters to clean up the brackets, you can use JavaScript's built-in **`JSON.parse()`** method to do it instantly in a single line!
❌ The Hard Way (Regex & Loops)
const cleanString = input.replace(/[\[\]]/g, '');
const items = cleanString.split(',');
const grid = [];
for (let i = 0; i < items.length; i += 2) {
grid.push([Number(items[i]), Number(items[i+1])]);
}
// Extremely tedious and prone to errors!
✅ The One-Line Way (JSON.parse)
const rawInput = "[[1,2],[3,4],[5,6]]"; // Converts directly into native JavaScript nested arrays! const grid = JSON.parse(rawInput); console.log(grid[0]); // Output: [1, 2] console.log(grid[1][1]); // Output: 4
Under the Hood: JS Event Vocabulary
When dealing with stream-based platforms, you will see events like on("line") or close. Here is what they actually mean:
Think of this as a listener waiting at the gate. Every time the operating system hits a newline character, it catches that text and passes it to your program.
This fires when there is absolutely no input left in the file stream. Use this callback as your signal to **finally** trigger your main calculations.
A function call that tells the operating system, *"I'm done reading from the input terminal. Stop listening and prepare to shutdown safely."*
Live CP Input Sandboxes
Interact with these playgrounds to test how JavaScript parses different strings and JSON structures live.
String ➔ Number Live Parser
Type any text block to see how the conversion methods behave.
Interactive JSON.parse Tool
Paste any raw grid array or complex object to verify native formatting.