Node.js Basics: JavaScript Outside the Browser
Modules and npm
In this lesson you will
- Share code between files with ES modules
- Describe package.json, node_modules and the lock file
- Install packages and run scripts with npm safely
Introduction
Real programs are made of many files. Modules let each file export what it offers and import what it needs. npm (Node Package Manager) lets you use code written by other people, called packages. Both are central to Node.
Two module systems
Node supports two styles, and you will meet both.
ES modules (ESM) are the modern, standard JavaScript way:
CommonJS (CJS) is the older Node style:
Both print 5. The file extension .mjs or .cjs tells Node which system a file uses. Plain .js files follow the "type" setting in package.json: "type": "module" means ESM, and the default is CommonJS. For new projects, choose ES modules.
Quick quiz
How can you tell Node that plain .js files in a project are ES modules?
Built-in modules
Node includes useful modules that you import by name, with the node: prefix to show they are built in:
package.json
Every project has a package.json, its identity card. Create one with:
Terminal
npm init -yIt looks like this:
JSON
{
"name": "demo",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node app.js"
}
}nameandversionidentify the project.typesets the module system.scriptsare shortcuts:npm startrunsnode app.js, andnpm run nameruns any other script.dependencieslists packages the project needs (added when you install).
Installing packages
Terminal
npm install expressThis downloads the package into a node_modules folder and records it in package.json. A package-lock.json file records the exact versions installed, so everyone gets the same ones. Commit package.json and the lock file to Git, but not node_modules.
Version numbers like ^5.1.0 follow semantic versioning: major, minor, patch. The caret allows minor and patch updates, but not a new major version, which may break things.
Using packages safely
Packages are code that runs on your machine, so treat them carefully.
- Prefer well-known, maintained packages with many users and recent updates.
- Check the name carefully, because attackers publish look-alike names.
- Keep dependencies few and up to date.
- Run
npm auditto see known vulnerabilities. - Do not run commands or install scripts from sources you do not trust.
- Remove packages you no longer use with
npm uninstall.
Try it yourself
Create a folder, run npm init -y, set "type": "module", write lib.js that exports a function, import it in main.js and add a start script. Run it with npm start.
Summary
- Modules share code between files. Use ES modules (
importandexport) for new projects. package.jsondescribes the project, the lock file pins versions, andnode_modulesis not committed.- Install packages with npm carefully, and keep dependencies few, updated and audited.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading