Python javascript node

Where Python, JavaScript and Node.js each run, what each one can do, and how they fit together, with working examples.

The short version

Python and JavaScript are programming languages. Node.js isn't a language: it's a way to run JavaScript outside a browser, on a computer with no screen and no page. The big difference between all of them isn't the syntax. It's where the code runs and what it's allowed to touch.

textwhere-things-run.txt
┌──────────────────────────┐              ┌──────────────────────┐
│ BROWSER  (the client)    │              │ SERVER               │
│                          │              │                      │
│ HTML  what's on the page │              │ Python   (Flask)     │
│ CSS   how it looks       │ the internet │    or                │
│ JS    what it does       │◄────────────►│ Node.js  (Express)   │
│                          │              │                      │
│ Runs on YOUR computer    │              │ Runs on a computer   │
│                          │              │ somewhere else       │
└──────────────────────────┘              └──────────────────────┘
  • The browser runs HTML, CSS and JavaScript. Everything arrives from a server and runs on the visitor's own computer.
  • A server is just a computer you control. Python or Node.js programs run there, with no page and no buttons, only a terminal.
  • JavaScript is the same language in both places. What changes is the toolbox: a browser has a page to change, and Node.js has files and servers.

What runs in the browser

A website is a folder of files. The browser downloads them and does everything itself: HTML says what's on the page, CSS says how it looks, JavaScript says what it does. Click through the files in the explorer.

htmlwebsite/index.html
<!DOCTYPE html>
<html>
  <head>
    <title>My first page</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <h1>Hello!</h1>
    <img src="images/cat.png" alt="A cat" />
    <button id="greet">Say hi</button>
    <p id="message"></p>

    <script src="script.js"></script>
  </body>
</html>

None of this needs Python or Node.js. You could double-click index.html and it works.

Python on a server

On its own, Python is just a program. There's no page and no buttons: it runs, prints text to a terminal, and stops. Here's a small project, and what you see when you run it.

pythonpython-project/main.py
from math_helpers import add, subtract, multiply, greet

print("Hello from Python!")
print(greet("Jay"))
print("2 + 3 =", add(2, 3))
print("10 - 4 =", subtract(10, 4))
print("6 x 7 =", multiply(6, 7))

# a list and a loop
for number in [1, 2, 3]:
    print("number:", number)

A server is just a computer that runs programs like this one and answers requests from other computers. There's nothing special about the hardware.

Node.js on a server

Node.js is the same idea with JavaScript. There's still no page, just a terminal. Look at how little changes: console.log instead of print, and function instead of def. The output is identical.

javascriptnode-project/main.js
import { add, subtract, multiply, greet } from "./mathHelpers.js";

console.log("Hello from Node!");
console.log(greet("Jay"));
console.log("2 + 3 =", add(2, 3));
console.log("10 - 4 =", subtract(10, 4));
console.log("6 x 7 =", multiply(6, 7));

// an array and a loop
for (const number of [1, 2, 3]) {
  console.log("number:", number);
}

The same program in both

The same little program in Python and in JavaScript, with a cheat sheet for what lines up with what.

pythonpython/main.py
def add(a, b):
    return a + b


name = "Jay"
numbers = [1, 2, 3]

print("Hello,", name)

for n in numbers:
    if n > 2:
        print(n, "is big")
    else:
        print(n, "is small")

print("2 + 3 =", add(2, 3))

How Python makes webpages

Flask is a Python library for building a web server. A browser asks it for a page, and Python answers. There are two ways Python and the page work together:

  • Templating. The HTML has blanks like {{ name }}. Python fills them in and sends the finished page. The browser never sees the Python.
  • Requests. JavaScript in the page asks Python for data with fetch() and gets an answer back, without reloading the page.
pythonflask-app/app.py
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)


@app.route("/")
def home():
    # Python fills in the blanks in templates/index.html
    return render_template("index.html", name="Jay", items=["apples", "bread", "milk"])


@app.route("/api/add")
def add():
    # Called by the JavaScript in the page: /api/add?a=2&b=3
    a = int(request.args["a"])
    b = int(request.args["b"])
    return jsonify(result=a + b)


if __name__ == "__main__":
    app.run(debug=True)

Node.js versus the browser

Node.js and browser JavaScript are the same language with different toolboxes. Browsers have document and window. Node.js has the file system and can run a server. Each is missing what the other has, and for good reasons: a server has no page to change, and a browser shouldn't be able to read your files.

textnode-vs-browser.txt
┌──────────────────────────────────┐  ┌──────────────────────────────────┐
│ NODE.JS  (on a server)           │  │ BROWSER  (on your computer)      │
│                                  │  │                                  │
│ Same language: JavaScript        │  │ Same language: JavaScript        │
│                                  │  │                                  │
│ CAN                              │  │ CAN                              │
│   read and write files           │  │   change the page (the DOM)      │
│   run a web server               │  │   react to clicks and typing     │
│   talk to databases              │  │   use the camera, if you allow it│
│   keep secrets (API keys)        │  │   fetch() data from a server     │
│                                  │  │                                  │
│ CAN'T                            │  │ CAN'T                            │
│   see a page or a screen         │  │   read your files on its own     │
│   use document or window         │  │   run a web server               │
│   click, scroll, use a camera    │  │   keep secrets: anyone can read  │
│                                  │  │   all the code it receives       │
└──────────────────────────────────┘  └──────────────────────────────────┘

Removing a background, three ways

A background remover is a good test: it can run in the browser, in Python, or in Node.js. The result is the same. What differs is where the work happens, and who has to get the photo to it.

Before and after

textbefore-and-after.txt
photo.jpg                       photo.png

░░░░░░░░░░░░░░░░░░░░            ····················
░░░░░░░▄████▄░░░░░░░            ·······▄████▄·······
░░░░░░░██████░░░░░░░            ·······██████·······
░░░░░░░▀████▀░░░░░░░            ·······▀████▀·······
░░░░▄▄████████▄▄░░░░  ───────►  ····▄▄████████▄▄····
░░░██████████████░░░            ···██████████████···
░░░██████████████░░░            ···██████████████···

all one picture                 only the person is left
                                (· means transparent)

The code in each place

javascriptin-the-browser/remove-bg.js
// Runs in the visitor's browser. The photo never leaves their computer.
import { removeBackground } from "@imgly/background-removal";

const input = document.querySelector("#photo");
const output = document.querySelector("#result");

input.addEventListener("change", async () => {
  const file = input.files[0];
  const blob = await removeBackground(file);  // a PNG with a transparent background
  output.src = URL.createObjectURL(blob);     // show it on the page
});
  • In the browser, the work happens on the visitor's own computer. The photo never leaves it, and you pay for nothing. But the visitor's phone does the heavy lifting, and has to download the model first.
  • On a Python or Node.js server, the work happens on your computer. It's consistent and fast, but the visitor has to send you the photo, and you pay for the server.

These show the shape of each approach, not copy-and-paste code. Package names and options change, so check each library's docs before using one.

Getting the server's result back to the user

A server can't hand a file to someone's browser by itself. The browser has to ask. The page sends the photo with fetch(), the server does the work and answers with the new image, and the page shows it. The server side works the same in Python and in Node.js.

textflow.txt
┌───────────────────────┐                    ┌────────────────────────┐
│ USER'S BROWSER        │                    │ SERVER                 │
│                       │                    │                        │
│ 1. picks photo.jpg    │  POST /remove-bg   │ 2. receives the file,  │
│    (with background)  │ ─────────────────► │    removes the         │
│                       │    (the photo)     │    background          │
│                       │                    │    (Python or Node.js) │
│                       │                    │                        │
│ 3. shows photo.png    │  the finished PNG  │                        │
│    (no background)    │ ◄───────────────── │                        │
│                       │                    │                        │
└───────────────────────┘                    └────────────────────────┘

Cheat sheet

PythonJavaScript in a browserNode.js
The languagePythonJavaScriptJavaScript
Where it runsA server, or your own computerThe visitor's browserA server, or your own computer
Has a page to changeNoYes (the DOM)No
Reads filesYesOnly ones the user picksYes
Makes webpages byFilling in HTML templates (Flask, Django)It is the code inside the webpageTemplates or JSON (Express and friends)
Packagespip installnpm install, then bundled into the pagenpm install
Run it withpython main.pyOpen the HTML filenode main.js