Node.js Foundations·From script to service

The runtime and modules

Node runs JavaScript outside the browser and gives it files, processes and modules.

Intermediate 12 min read Lesson 6 of 300 Challenge included
What you will be able to do
  • Use import and export with "type": "module" in package.json.
  • Read configuration from environment variables, never hard-code secrets.
  • Keep startup code separate from testable module code.

In plain English

Node uses an event loop and non-blocking I/O. ES modules are the modern default. The package.json file records dependencies and scripts; the engines field documents the runtime you support.

server.mjsJavaScript
import { createServer } from 'node:http'

const port = Number(process.env.PORT || 3000)

const server = createServer((request, response) => {
  response.writeHead(200, { 'content-type': 'application/json' })
  response.end(JSON.stringify({ ok: true, path: request.url }))
})

server.listen(port, () => {
  console.log('Listening on ' + port)
})
Your turn

Read a port safely

Easy

Read PORT from the environment and fall back to 3000. Print the value as a number.

JS · starter
const port = process.env.PORT
Check your understanding before moving on.
Knowledge checkQuestion 1

What does the engines field in package.json communicate?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: A JSON HTTP API
Lesson 6 of 300 · 0% of course