What you'll learn
What Node.js is, how it differs from browser JavaScript, and how to run a file with node.
Why it matters
Node lets you use one language, JavaScript, for both the front end and the back end. Servers, command-line tools and build tools for React and many other frameworks all run on Node.
Explanation
JavaScript was created to run inside web browsers. Node.js is a program that runs JavaScript on your own computer, outside a browser. It uses the same engine as Chrome (V8) but adds things a browser does not have: access to files, the network and your operating system.
Because there is no web page, there is no document or window. Instead you get Node features such as process, require / import, and modules like fs and http.
You run a script from a terminal:
node hello.jsExample
Save this as hello.js and run node hello.js:
const name = "Asha";
console.log("Hello from Node,", name);
console.log("Node version is a string:", typeof process.version);
console.log("2 + 3 =", 2 + 3);Step-by-step walkthrough
node hello.jsstarts Node and tells it to run the file.- Node runs each line top to bottom, like in the browser.
console.logprints to your terminal instead of the browser console.process.versionis a Node-only value. We print its type, which is alwaysstring.
Try it yourself
Change the name, add another console.log, and run the file again. Press the button to see the expected output.
Common mistakes
- Using browser-only things like
documentoralert. They do not exist in Node. - Running from the wrong folder, so
node hello.jssays "Cannot find module". - Forgetting to save the file before running.
- Installing the wrong version. Use the LTS (long-term support) release.
Quick quiz
Summary
- Node.js runs JavaScript outside the browser.
- It has no
document, but it has files, network andprocess. - Run scripts with
node file.js.
Next: splitting code into modules.