JavaScript:Node.js Stdin Input: Reading Multi-Line Input with fs.readFileSync(0)
JavaScript•Stdin Parsing

Node.js Stdin Input: Reading Multi-Line Input with fs.readFileSync(0)

Compilra executes JavaScript on Node.js 22 with pre-supplied stdin sent before clicking Run. Instead of setting up asynchronous readline listeners, reading file descriptor 0 synchronously with fs.readFileSync(0, "utf8") gives you all lines immediately for fast parsing.

Syntax

const lines = fs.readFileSync(0, "utf8").trim().split(/\r?\n/);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
fs.readFileSync(0, "utf8")stringReads the complete pre-supplied standard input from file descriptor 0 as UTF-8 text.
.trim().split(/\r?\n/)string[]Trims leading/trailing whitespace and splits lines across LF and CRLF endings.
Number()numberConverts string numeric tokens into JavaScript numbers cleanly.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing JavaScript locally:

const fs = require("fs");

const raw = fs.readFileSync(0, "utf8").trim();
const lines = raw ? raw.split(/\r?\n/) : [];
const caseCount = Number(lines[0]);

for (let i = 1; i <= caseCount; i++) {
  const nums = lines[i]
    .trim()
    .split(/\s+/)
    .map(Number);
  const total = nums.reduce((acc, n) => acc + n, 0);
  console.log(`Case #${i}: items=${nums.length}, total=${total}`);
}
Pre-Supplied Stdin (Input):
3
5 10 20
7 8
100
Expected Output:
Case #1: items=3, total=35
Case #2: items=2, total=15
Case #3: items=1, total=100

How It Works: Step-by-Step

  • Lines 3-5: Reads all pre-supplied stdin text from fd 0, splits lines, and parses caseCount.
  • Lines 7-11: Splits each case line on whitespace (/\s+/) and converts each token to Number.
  • Lines 12-13: Computes the sum with Array.prototype.reduce and logs each formatted summary.

Key Concepts

  • Enter test cases in Compilra’s Standard Input (stdin) panel before clicking Run—stdin is sent upfront rather than typed interactively.
  • Browser APIs like prompt() or alert() do not exist in Node.js 22; use fs.readFileSync(0, "utf8") for command-line stdin.
  • Guarding raw ? raw.split(...) : [] prevents an empty array element [""] when no stdin is provided.

Common Mistake: Calling browser prompt() in a Node.js execution environment

Node.js has no window.prompt() dialog. Calling prompt() throws ReferenceError: prompt is not defined.

❌ Incorrect
const name = prompt("Enter name:"); // ReferenceError in Node.js!
✅ Correct
const fs = require("fs");
const name = fs.readFileSync(0, "utf8").trim();

Related JavaScript Tutorials & Compiler

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler