Web development guide

Node.js Basics: Run JavaScript Outside the Browser

Node.js runs JavaScript on your computer or a server, so you can build command-line tools, APIs and websites with one language.

Install and check

Download the LTS (long-term support) version from nodejs.org, then check it in a terminal:

node -v
npm -v

Run your first script

Create hello.js and run it with node hello.js.

const name = "Node";
console.log(`Hello from ${name}`);

Create a simple web server

The built-in http module needs no extra packages.

const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("It works!");
});

server.listen(3000, () => console.log("Open http://localhost:3000"));

Use npm packages

Create a project and install a package such as Express, a popular web framework:

npm init -y
npm install express

Packages and their versions are recorded in package.json. Share that file, not the node_modules folder.

Understand async code

Reading files and calling APIs take time, so Node uses asynchronous code. async/await keeps it readable:

const fs = require("fs/promises");

async function main() {
  const text = await fs.readFile("notes.txt", "utf8");
  console.log(text.length, "characters");
}
main().catch(console.error);

Good habits

  • Keep secrets such as API keys in environment variables, never in your code or in Git.
  • Review and update dependencies regularly, and install only packages you trust.
  • Handle errors; an unhandled error can stop your server.
  • Learn how requests and responses work with our REST API basics guide.

Frequently asked questions

What is the difference between Node.js and JavaScript?

JavaScript is the language. Node.js is a runtime that lets that language run outside a browser.

Do I need npm?

Not for simple scripts, but npm gives you access to a huge library of packages.

Which version should I install?

Choose the LTS version for stable projects.

← Back to Web Development