Back end with Node

Level recap · Back end with Node · Level 1

Node basics

Everything this level taught, class by class: the idea, the code and what it shows. Read it before the exam, or keep it as a PDF.

What this level teaches: Write programs that read and change files and run from the terminal.

11 classesLevel exam

Take the level exam
  1. 1Your first Node program

    Node runs JavaScript outside the browser.

    The idea

    Ticket CL-301 from the back-end lead: the shop's order tools are moving from the browser to the server, and on the server they run on Node.

    Node runs JavaScript outside the browser: on a server, or on your own computer from a terminal. You save the code in a file and run it with node index.js. Here your file runs on a practice copy of Node, so Your screen shows what a terminal would print.

    The code

    console.log("Copperleaf order tools");
    console.log("Running on Node " + process.version);

    What it shows

    PASS The first line says Copperleaf order tools
  2. 2Modules: require and module.exports

    Use code from another file, and share your own.

    The idea

    Ticket CL-302: finance keeps the tax rule in one file, tax.js, so every tool uses the same rate. When the rate changes, only that file changes.

    In Node, each file is a module. What a file puts on module.exports is what other files get when they require it: const { withTax } = require("./tax"); gives you the withTax function from tax.js. The ./ means "a file next to this one".

    The code

    const { withTax } = require("./tax");
    function orderTotal(prices) {
      let total = 0;
      for (const p of prices) total += withTax(p);
      return Math.round(total * 100) / 100;
    }
    console.log(orderTotal([20, 5.5]));
    module.exports = { orderTotal };

    What it shows

    PASS orderTotal is exported and adds the prices with tax
  3. 3Words after the file name

    process.argv, and an exit code when the tool is used wrong.

    The idea

    Ticket CL-303: warehouse staff start their shift with a small tool in the terminal: node index.js Omar 3 greets Omar and tells him his dock.

    process.argv is an array of strings. Item 0 is the path of Node itself, item 1 is the path of your file, and from item 2 on come the words typed after the file name. So process.argv.slice(2) gives just those words: ["Omar", "3"].

    The code

    const [name, dock] = process.argv.slice(2);
    if (!name || !dock) {
      console.error("Usage: node index.js <name> <dock>");
      process.exit(1);
    }
    console.log("Hello, " + name + ". Your dock today is " + dock + ".");

    What it shows

    PASS It greets the person with their dock, from the words typed
  4. 4Read a file

    fs.readFileSync, and a file split into lines.

    The idea

    Ticket CL-304: the warehouse exports the stock count as a text file, stock.txt, one product per line: Desk lamp,12. The team lead wants each line shown and the total number of units at the end.

    Node's fs module reads and writes files: const fs = require("fs");. fs.readFileSync("stock.txt", "utf8") gives back the whole file as one string. Without "utf8" you get a Buffer, the raw bytes.

    The code

    const fs = require("fs");
    const text = fs.readFileSync("stock.txt", "utf8");
    let total = 0;
    for (const line of text.split("\n")) {
      if (!line.trim()) continue;
      const [name, count] = line.split(",");
      console.log(name + ": " + count);
      total += Number(count);
    }
    console.log("Total units: " + total);

    What it shows

    PASS Each line of the file is printed as name: count
  5. 5Write a report file

    fs.writeFileSync makes a file other people can open.

    The idea

    Ticket CL-305: the shift manager wants the day's orders as a plain report file she can email: report.txt, made from orders.csv.

    fs.writeFileSync("report.txt", text) writes the string to the file. It makes the file when it is not there and replaces it when it is. It writes exactly what you give it, so put "\n" between lines (lines.join("\n")).

    The code

    const fs = require("fs");
    const rows = fs.readFileSync("orders.csv", "utf8").split("\n").slice(1).filter((l) => l.trim());
    const lines = [];
    let total = 0;
    for (const row of rows) {
      const [id, item, qty, price] = row.split(",");
      const amount = Number(qty) * Number(price);
      total += amount;
      lines.push(id + ": " + qty + " x " + item + " = $" + amount.toFixed(2));
    }
    lines.push("Total: $" + total.toFixed(2));
    fs.writeFileSync("report.txt", lines.join("\n") + "\n");
    console.log("Report saved: " + rows.length + " orders");

    What it shows

    PASS report.txt has one line per order with its amount
  6. 6Paths that work on any machine

    path.join, path.extname and the files in a folder.

    The idea

    Ticket CL-306: suppliers drop their price lists into the uploads folder. Some are .csv, some are photos and notes. The buyer needs the list of .csv files with their sizes.

    Building paths by hand with + "/" breaks easily. The path module does it right: path.join(__dirname, "uploads") is the uploads folder next to your file, wherever the project is. __dirname is the folder of the running file. path.extname("prices.csv") gives ".csv", and path.basename("prices.csv", ".csv") gives "prices".

    The code

    const fs = require("fs");
    const path = require("path");
    const folder = path.join(__dirname, "uploads");
    for (const name of fs.readdirSync(folder)) {
      if (path.extname(name) !== ".csv") continue;
      const size = fs.statSync(path.join(folder, name)).size;
      console.log(path.basename(name, ".csv") + ": " + size + " bytes");
    }

    What it shows

    PASS Only the .csv files are listed, by name without .csv
  7. 7Change a JSON file

    JSON.parse, change the data, JSON.stringify back.

    The idea

    Ticket CL-307: when a delivery arrives, the warehouse updates inventory.json from the terminal: node index.js 12 -3 takes 3 units off product 12.

    JSON.parse(text) turns the file's text into real arrays and objects you can change. JSON.stringify(data, null, 2) turns them back into text with two spaces of indent, so the file stays readable for the next person.

    The code

    const fs = require("fs");
    const [id, change] = process.argv.slice(2).map(Number);
    const products = JSON.parse(fs.readFileSync("inventory.json", "utf8"));
    const p = products.find((x) => x.id === id);
    if (!p) {
      console.error("No product with id " + id);
      process.exit(1);
    }
    const before = p.stock;
    p.stock += change;
    fs.writeFileSync("inventory.json", JSON.stringify(products, null, 2));
    console.log(p.name + ": " + before + " -> " + p.stock);

    What it shows

    PASS The product's stock changes in the file, and only that product
  8. 8When a file is not there

    try/catch, and error codes like ENOENT.

    The idea

    Ticket CL-308: the returns tool crashes every morning before the first return comes in, because returns.log does not exist yet. Support wants a calm message instead.

    When readFileSync cannot find a file, it throws an error. Catch it with try { ... } catch (err) { ... }. Node errors carry a code: "ENOENT" means no such file, "EISDIR" means the path is a folder, "EACCES" means no permission.

    The code

    const fs = require("fs");
    try {
      const text = fs.readFileSync("returns.log", "utf8");
      const count = text.split("\n").filter((l) => l.trim()).length;
      console.log("Returns today: " + count);
    } catch (err) {
      if (err.code !== "ENOENT") throw err;
      console.log("No returns yet.");
    }

    What it shows

    PASS With a log file, it counts the returns
  9. 9Settings from the environment

    process.env, with a default when a setting is missing.

    The idea

    Ticket CL-309: each warehouse wants its own low-stock limit. The ops team sets it on the server, without changing the code.

    Servers pass settings to programs through environment variables. In Node they are on process.env: process.env.LOW_STOCK is the text "8" when the server sets LOW_STOCK=8, and undefined when it is not set.

    The code

    const fs = require("fs");
    const products = JSON.parse(fs.readFileSync("inventory.json", "utf8"));
    const limit = Number(process.env.LOW_STOCK ?? 5);
    console.log("Low stock (below " + limit + "):");
    for (const p of products) {
      if (p.stock < limit) console.log(p.name + ": " + p.stock);
    }

    What it shows

    PASS With LOW_STOCK set, it uses that limit
  10. 10A command-line tool

    Commands, a file that keeps the data, and a usage line.

    The idea

    Ticket CL-310: the support team wants a to-do tool in the terminal: node index.js add Call the courier, node index.js list and node index.js done 2.

    A command-line tool reads the first word as the command and the rest as its details: const [cmd, ...rest] = process.argv.slice(2);. Each run is a new program, so the tool keeps its data in a file, tasks.json, read at the start and written after a change. The first run has no file yet: start with an empty list.

    The code

    const fs = require("fs");
    const [cmd, ...rest] = process.argv.slice(2);
    const tasks = fs.existsSync("tasks.json") ? JSON.parse(fs.readFileSync("tasks.json", "utf8")) : [];
    const save = () => fs.writeFileSync("tasks.json", JSON.stringify(tasks, null, 2));
    if (cmd === "add" && rest.length) {
      tasks.push({ title: rest.join(" "), done: false });
      save();
      console.log("Added: " + rest.join(" "));
    } else if (cmd === "list") {
      tasks.forEach((x, i) => console.log((i + 1) + ". [" + (x.done ? "x" : " ") + "] " + x.title));
    } else if (cmd === "done" && tasks[Number(rest[0]) - 1]) {
      tasks[Number(rest[0]) - 1].done = true;
      save();
      console.log("Done: " + tasks[Number(rest[0]) - 1].title);
    } else {
      console.error("Usage: node index.js add <title> | list | done <n>");
      process.exit(1);
    }

    What it shows

    PASS add keeps tasks between runs, and list shows them in order
  11. 11Read files without waiting in line

    fs/promises, async/await and Promise.all.

    The idea

    Ticket CL-311: the weekly sales report reads one file per day. On the server, reading them one after the other keeps everyone else waiting.

    require("fs/promises") gives versions of the file functions that give back a promise: await readFile("sales/mon.json", "utf8") waits for the file without stopping the rest of the server. await works inside an async function, so put the work in async function main() and call main().

    The code

    const { readFile } = require("fs/promises");
    const days = ["mon", "tue", "wed", "thu", "fri"];
    async function main() {
      try {
        const texts = await Promise.all(days.map((d) => readFile("sales/" + d + ".json", "utf8")));
        const total = texts.reduce((sum, text) => sum + JSON.parse(text).total, 0);
        console.log("Week total: $" + total.toFixed(2));
      } catch (err) {
        console.error("Could not read the sales files: " + err.message);
        process.exitCode = 1;
      }
    }
    main();

    What it shows

    PASS It adds up the five days

Ready for the exam? The level exam is one real task that uses what this recap covers.

Take the level exam