These are the notes for JavaScript episode 14. You will learn why values written inside the code don't scale, why prompt fails in Node.js (ReferenceError: prompt is not defined), what standard input (stdin) is, how to read it with require("fs").readFileSync(0, "utf8"), why input is always a string ("10" + "20" is "1020"), converting with Number(), splitting into words and lines, the trailing newline bug and trim(), validating what people type, reading line by line with readline, and a mini project: a bill built from typed orders. Every example runs as-is in the SyntaxPilot compiler (language: JavaScript, Node.js): type the input into the compiler's input box before you press Run.
The problem: values stuck in the code
const qty = 3;
const price = 10;
console.log(`${qty} chai = Rs ${qty * price}`);
3 chai = Rs 30
Correct, but only ever for 3 chai. For a customer who wants 5, Ravi must open the code, edit it and run it again. A real program asks: the code stays the same and the values come from outside each time it runs. That's called input.
prompt? Not in Node.js
const qty = prompt("How many chai?");
console.log(`Bill: Rs ${qty * 10}`);
const qty = prompt("How many chai?");
^
ReferenceError: prompt is not defined
prompt belongs to the browser: it pops up a box in a window. Node.js runs JavaScript in a terminal, with no window, so it has no prompt (and no alert, document or window). The browser and Node are two different homes for JavaScript, with different built-in tools (episode 1).
stdin: the kitchen hatch
| A restaurant kitchen | In Node.js | Name |
|---|---|---|
| The waiter writes the order slip outside | the user types into the input box or terminal | input |
| Slips come through one hatch in the wall | the program's incoming text stream, number 0 | stdin (standard input) |
| The cook reads the slip; the recipe never changes | fs.readFileSync(0, "utf8") |
reading stdin as text |
const fs = require("fs");
const input = fs.readFileSync(0, "utf8");
console.log("You typed:", input);
console.log([input]);
console.log(typeof input);
Input: 3 then Enter.
You typed: 3
[ '3\n' ]
string
require("fs")loads Node's built-in file system module (modules are episode 18).readFileSync(0, "utf8")reads everything waiting on stdin.0is stdin's number (its file descriptor);"utf8"means "give me text, not raw bytes".- Printing inside
[ ]shows hidden characters:\nis the newline from the Enter key. typeof inputis"string". Input is always a string, even when you type a number.
Every program also has stdout (standard output, number 1: where console.log writes) and stderr (standard error, number 2: where error messages go).
Strings to numbers
Two quantities on one line:
const input = require("fs").readFileSync(0, "utf8");
const [a, b] = input.split(" ");
console.log(a + b);
console.log(Number(a) + Number(b));
Input: 10 20
1020
30
split(" ")cuts the string at each space:["10", "20\n"]. Array destructuring (episode 12) takes the two parts.a + bglues two strings (episode 3):"1020"followed by the newline, hence the empty line.Number(text)converts:Number("20\n")is20, because spaces and newlines around a number are ignored.
| Expression | Result |
|---|---|
Number(" 3 ") |
3 |
Number("two") |
NaN |
Number("3 chai") |
NaN |
Number("") |
0 (!) |
parseInt("3 chai") |
3 (reads digits until the first non-digit) |
Many lines, and the phantom order bug
One quantity per line, split("\n") cuts at each newline and map(Number) (episode 11) converts each line:
const fs = require("fs");
const input = fs.readFileSync(0, "utf8");
const lines = input.split("\n");
console.log(lines);
const qtys = lines.map(Number);
console.log(qtys);
Input: 3, 5, 2, each followed by Enter.
[ '3', '5', '2', '' ]
[ 3, 5, 2, 0 ]
A fourth, empty line, and a phantom order of 0 that nobody typed. The last Enter left a \n at the very end; split sees an empty string after it, and Number("") is 0, not NaN, so nothing warns you.
Fix: trim() first. It removes spaces and newlines from both ends of a string.
const fs = require("fs");
const input = fs.readFileSync(0, "utf8");
const lines = input.trim().split("\n");
console.log(lines);
const qtys = lines.map(Number);
console.log(qtys);
[ '3', '5', '2' ]
[ 3, 5, 2 ]
The recipe: read → trim() → split("\n") (lines) or split(" ") (words) → Number() → check.
Windows tip: text typed on Windows may end lines with \r\n. trim() only cleans the two ends, so the inner lines keep a \r. split(/\r?\n/) handles both (regular expressions are episode 23), or trim() each line.
Checking what people type
Never trust input. Check every value before you use it:
const fs = require("fs");
const lines = fs.readFileSync(0, "utf8").trim().split("\n");
let total = 0;
for (const line of lines) {
const qty = Number(line);
if (!Number.isInteger(qty) || qty <= 0) {
console.log(`Skipping "${line}": not a quantity`);
continue;
}
total += qty;
}
console.log(`Total chai: ${total}`);
Input: 3, two, 5, an empty line, -1, 2.
Skipping "two": not a quantity
Skipping "": not a quantity
Skipping "-1": not a quantity
Total chai: 10
Number.isInteger(x) is true only for whole numbers, so it rejects NaN too. Without the check, the empty line adds 0 silently and "two" turns the whole total into NaN.
Line by line: readline
readFileSync waits for all the input, then reads it in one go: perfect for the compiler's input box and for coding-contest style problems. For a program that reacts to each line as it arrives (a chat, an interactive menu), Node has the readline module:
const readline = require("readline");
const rl = readline.createInterface({ input: process.stdin });
let count = 0;
rl.on("line", (line) => {
count++;
console.log(`Order ${count}: ${line}`);
});
rl.on("close", () => {
console.log(`${count} orders received`);
});
console.log("Waiting for orders...");
Input: chai, samosa, jalebi.
Waiting for orders...
Order 1: chai
Order 2: samosa
Order 3: jalebi
3 orders received
process.stdinis stdin as a stream (data that arrives over time).rl.on("line", fn)doesn't runfnnow: it registers it to be called later, once per line.rl.on("close", fn)runs when the input ends.- That's why
Waiting for orders..., the last line of the code, prints first. Functions that run later, when something happens, are called event handlers (or callbacks); the event loop episode (24) explains exactly how this works.
Common mistakes (and what really happens)
| You wrote | What happens | Why | Fix |
|---|---|---|---|
prompt("How many?") |
ReferenceError: prompt is not defined |
prompt is browser-only |
require("fs").readFileSync(0, "utf8") |
a + b with values from input |
(no error) "10" + "20" is "1020" |
input is a string | Number(a) + Number(b) |
input.split("\n") |
(no error) [ '3', '5', '2', '' ] → a phantom 0 |
the last Enter | input.trim().split("\n") |
Number("two") used directly |
(no error) NaN spreads through the maths |
not a number | check with Number.isInteger |
"10 20".split(" ") |
(no error) [ '10', '', '20' ] |
two spaces = an empty word between them | .filter((w) => w !== "") |
| Pressing Run with an empty input box | (no error) input is "" |
nothing was typed | check lines.length / empty lines |
Mini project: a bill from typed orders
The first line is the customer's name; every other line is an item and a quantity.
const fs = require("fs");
const menu = { chai: 10, samosa: 12, jalebi: 30 };
const [customer, ...rows] = fs.readFileSync(0, "utf8").trim().split("\n");
let total = 0;
console.log(`Bill for ${customer}`);
for (const row of rows) {
try {
const [item, qtyText] = row.trim().split(" ");
const qty = Number(qtyText);
if (!(item in menu)) throw new Error(`${item} is not on the menu`);
if (!Number.isInteger(qty) || qty <= 0) throw new Error(`bad quantity "${qtyText}"`);
total += qty * menu[item];
console.log(` ${item} x ${qty} = Rs ${qty * menu[item]}`);
} catch (err) {
console.log(` skipped: ${err.message}`);
}
}
console.log(`Total: Rs ${total}`);
Input:
Asha
chai 3
samosa two
pizza 1
jalebi 2
Output:
Bill for Asha
chai x 3 = Rs 30
skipped: bad quantity "two"
skipped: pizza is not on the menu
jalebi x 2 = Rs 60
Total: Rs 90
const [customer, ...rows]takes the first line, and rest (episode 12) gathers the others.- Each row is validated with
throw, andtry/catch(episode 13) skips a bad row with a reason instead of crashing. - Ravi can type any order, and the code never changes.
Practice
- Read two numbers on one line and print their sum, difference and product.
- Read marks, one per line, skip anything that isn't a number, and print the average.
- Extend the bill: a line
tip 20adds a tip to the total.
Solutions and hints
const [a, b] = require("fs").readFileSync(0, "utf8").trim().split(" ").map(Number);
console.log(`sum ${a + b}, difference ${a - b}, product ${a * b}`);
Input 12 5:
sum 17, difference 7, product 60
const lines = require("fs").readFileSync(0, "utf8").trim().split("\n");
const marks = [];
for (const line of lines) {
const m = Number(line);
if (line.trim() === "" || Number.isNaN(m)) {
console.log(`Not a mark: "${line}"`);
continue;
}
marks.push(m);
}
const avg = marks.reduce((sum, m) => sum + m, 0) / marks.length;
console.log(`Average of ${marks.length} marks: ${avg}`);
Input 80, 90, absent, 70:
Not a mark: "absent"
Average of 3 marks: 80
const fs = require("fs");
const menu = { chai: 10, samosa: 12, jalebi: 30 };
const [customer, ...rows] = fs.readFileSync(0, "utf8").trim().split("\n");
let total = 0;
for (const row of rows) {
const [item, qtyText] = row.trim().split(" ");
const qty = Number(qtyText);
if (item === "tip" && Number.isInteger(qty) && qty > 0) {
total += qty;
console.log(` tip = Rs ${qty}`);
} else if (item in menu && Number.isInteger(qty) && qty > 0) {
total += qty * menu[item];
console.log(` ${item} x ${qty} = Rs ${qty * menu[item]}`);
} else {
console.log(` skipped: "${row}"`);
}
}
console.log(`${customer} pays Rs ${total}`);
Input Asha, chai 2, tip 20:
chai x 2 = Rs 20
tip = Rs 20
Asha pays Rs 40
.map(Number)converts both words at once; destructuring unpacks them.- The empty-line check matters:
Number("")is0, which would pull the average down. - A special case is just one more branch before the menu check.
Quick quiz
The user types 4, Enter, 5, Enter. What prints?
const input = require("fs").readFileSync(0, "utf8");
const [a, b] = input.trim().split("\n");
console.log(a + b, Number(a) + Number(b));
- A.
9 9 - B.
45 9 - C.
4\n5 9 - D.
NaN 9
Answer
B. a and b are the strings "4" and "5", so + glues them into "45". After Number(), + really adds: 9.
Interview questions
- What are stdin, stdout and stderr?
- Why doesn't
promptwork in Node.js? - How do you read all of standard input in Node.js? What do
0and"utf8"mean? - Why is
"10" + "20"equal to"1020"? How do you fix it? - What's the difference between
Number("3 chai")andparseInt("3 chai")? What isNumber("")? - Why do you
trim()beforesplit("\n")? - When would you use
readlineinstead ofreadFileSync? - Why does
console.logafterrl.on("line", ...)print before the lines?
Glossary
| Term | Meaning | Example |
|---|---|---|
| Input | values that come from outside the program each time it runs | what the user types |
| stdin (standard input) | the stream of text coming into a program; number 0 | the compiler's input box |
| stdout (standard output) | where normal output goes; number 1 | console.log |
| stderr (standard error) | where error messages go; number 2 | a crash's stack trace |
| File descriptor | the number Node uses for an open stream or file | 0 for stdin |
| Module | a bundle of ready-made code you load | require("fs") |
fs |
Node's built-in file system module | fs.readFileSync(0, "utf8") |
require |
loads a module in Node (CommonJS) | const fs = require("fs"); |
| UTF-8 | the standard way to store text as bytes | "utf8" |
Newline \n |
the hidden character the Enter key adds | '3\n' |
trim() |
removes spaces and newlines from both ends | " 3\n".trim() → "3" |
split(sep) |
cuts a string into an array at each separator | "a b".split(" ") |
Number(text) |
converts text to a number (NaN if it can't) |
Number("42") |
NaN |
"Not a Number" | Number("two") |
| Validation | checking values before trusting them | Number.isInteger(qty) && qty > 0 |
| Stream | data that arrives a piece at a time | process.stdin |
readline |
Node module for reading a stream line by line | rl.on("line", fn) |
| Event handler / callback | a function you hand over to be called later, when something happens | (line) => { ... } |
prompt |
a browser-only function that asks the user in a pop-up | not in Node |
Summary
- Values written in the code are fixed; input makes the same code work for every customer.
- Node has no
prompt: it reads stdin.require("fs").readFileSync(0, "utf8")reads all of it as one string. - Input is always a string. Convert with
Number();+on strings glues. - read → trim → split → convert → check.
Number("")is0andNumber("two")isNaN, so validate. readlinereads line by line;rl.on("line", fn)callsfnlater, once per line.
Next episode: a basics project, a quiz game, using everything from episodes 1 to 14.