Please enable JavaScript to use CodeHS

Node.js Documentation

Basics

Printing to Console

console.log(str);
console.error(str);

// Example:
console.log("Hello, world!");

// Printing without a new line:
process.stdout.write("Hello, world. ");
process.stdout.write("How are you?");
  

Variables

// Declare and initialize variables
let myVarName = 5;  // Block-scoped
const myConstant = 10;  // Constant variable
var oldVar = 20;  // Function-scoped

// Assign to an existing variable
myVarName = 10;

// Print a variable
console.log(myVarName);
console.log("The value is: " + myVarName);
  

Functions

// Functions with parameters
function printText(input) {
  console.log(input);
}

// Arrow function syntax
const addTwo = (number) => {
  return number + 2;
};

// Inline arrow function
const multiplyByTwo = (number) => number * 2;
  

User Input

// Using the 'readline' module for input
const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question("What is your name? ", (name) => {
  console.log("Hello, " + name);
  rl.close();
});
  

Comparison Operators

// Comparison operators return booleans
x == y  // equality (loose)
x === y // strict equality
x != y  // not equal
x !== y // strict not equal
x > y   // greater than
x >= y  // greater than or equal
x < y   // less than
x <= y  // less than or equal

// In an if statement
if (x === y) {
  console.log("x and y are strictly equal");
}
if (x > 5) {
  console.log("x is greater than 5");
}
  

Math

// Math operators
let sum = x + y;
let product = x * y;

// Increment and decrement
x++;
x--;

// Shortcuts
x += y;
x -= y;
x *= y;
x /= y;

// Math methods
const abs = Math.abs(-10);  // 10
const sqrt = Math.sqrt(16); // 4
const rounded = Math.round(3.14); // 3
const floored = Math.floor(5.7); // 5
const ceiling = Math.ceil(5.1); // 6

// Random numbers
let random = Math.random();  // 0 <= random < 1
let randomInt = Math.floor(Math.random() * 10) + 1;  // Random 1-10
  

Loops

// For loop
for (let i = 0; i < 5; i++) {
  console.log("Iteration:", i);
}

// While loop
let count = 5;
while (count > 0) {
  console.log(count);
  count--;
}

// Do-while loop
let num = 0;
do {
  console.log(num);
  num++;
} while (num < 5);
  

Timers

// Timers in Node.js
setTimeout(() => {
  console.log("This runs after 2 seconds");
}, 2000);

let interval = setInterval(() => {
  console.log("Repeating every 1 second");
}, 1000);

// Stop the timer
setTimeout(() => {
  clearInterval(interval);
  console.log("Timer stopped");
}, 5000);
  

Events

// Event Emitter in Node.js
const EventEmitter = require("events");
const emitter = new EventEmitter();

// Register an event
emitter.on("myEvent", (arg) => {
  console.log("Event triggered with:", arg);
});

// Emit the event
emitter.emit("myEvent", "some data");
  

Modules

// Exporting a module
// File: myModule.js
exports.sayHello = (name) => {
  console.log("Hello, " + name);
};

// Importing a module
// File: app.js
const myModule = require("./myModule");
myModule.sayHello("John");
  

Reading and Writing Files

const fs = require("fs");

// Writing to a file
fs.writeFile("example.txt", "Hello, world!", (err) => {
  if (err) throw err;
  console.log("File created!");
});

// Reading from a file
fs.readFile("example.txt", "utf8", (err, data) => {
  if (err) throw err;
  console.log("File content:", data);
});
  

Asynchronous Programming

// Callback example
fs.readFile("example.txt", "utf8", (err, data) => {
  if (err) return console.error(err);
  console.log("File content:", data);
});

// Promises
const readFile = (filename) => {
  return new Promise((resolve, reject) => {
    fs.readFile(filename, "utf8", (err, data) => {
      if (err) reject(err);
      else resolve(data);
    });
  });
};

readFile("example.txt")
  .then((data) => console.log("Content:", data))
  .catch((err) => console.error(err));

// Async/Await
const main = async () => {
  try {
    const data = await readFile("example.txt");
    console.log("Content:", data);
  } catch (err) {
    console.error(err);
  }
};
main();
  

HTTP Server

const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello, Node.js HTTP Server!");
});

server.listen(3000, () => {
  console.log("Server is running on http://localhost:3000");
});
  

Data Structures

Arrays

// Create an array
const fruits = ["apple", "banana", "cherry"];

// Access an element
console.log(fruits[0]); // "apple"

// Add an element
fruits.push("date"); // Adds to the end

// Remove an element
fruits.pop(); // Removes the last element

// Loop through an array
for (let fruit of fruits) {
  console.log(fruit);
}
  

Maps/Objects

// Using an Object
const user = {
  name: "Alice",
  age: 25
};

// Access a property
console.log(user.name); // "Alice"

// Add a property
user.email = "alice@example.com";

// Delete a property
delete user.age;
  

Sets

// Create a Set
const mySet = new Set();

// Add elements
mySet.add(1);
mySet.add(2);

// Check if an element exists
console.log(mySet.has(1)); // true

// Loop through a Set
for (let value of mySet) {
  console.log(value);
}
  

Working with JSON

const jsonString = '{"name": "John", "age": 30}';

// Parse JSON string into an object
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name);  // John

// Convert object to JSON string
const jsonOutput = JSON.stringify(jsonObject);
console.log(jsonOutput);