Lesson 1
Node.js basics: npm, packages and scripts
What you will learn
- Make a new Node.js project with
npm init. - Read what
package.jsonsays about your project. - Write a script that reads the Chai Corner
products.jsonfile. - Install a package from npm and use it.
- Run your scripts with
npm run.
What it is
Node.js scripts
In Track 0 you ran JavaScript in the browser. Node.js runs the same language on your computer, with no browser.
A script is a JavaScript file that you run with Node.js. It is like a recipe card. Node.js reads it from top to bottom and does each step.
A browser script can change a page. A Node.js script can do other jobs, like read and write files on your computer.
Packages and npm
A package is a folder of ready-made code that someone shared. It is like a spice mix. You buy it ready, so you do not grind every spice yourself.
npm is the store for packages, and it is also the tool that downloads them. A package your project needs is called a dependency.
package.json
package.json is the ID card of your project. It lists the project name, its scripts and its packages. Every Node.js project has one in its main folder.
node_modules and package-lock.json
node_modules is the folder where npm puts the packages it downloads. Think of it as the kitchen store room. You never cook in it, but the spices live there.
You never edit node_modules by hand.
You can delete it at any time. npm install brings it back.
package-lock.json writes down the exact version of every package npm installed. It helps every computer install the same versions.
npm scripts
An npm script is a short name for a command, saved in package.json.
It is like a speed dial on a phone.
You type npm run start instead of the full command.
Why you need it
- Shopify CLI runs on Node.js. Shopify's docs ask for Node.js 22.12 or higher.
- A Shopify app is a Node.js project. Its
package.jsonlists its packages and its npm scripts. - You start, build and test a Shopify app with npm scripts, like
npm run dev. - Every lesson in this track installs packages with npm.
Before you start
- Open VS Code.
- Open the terminal with Terminal > New Terminal.
- Go to the folder where you keep your projects, for example
Documents.
Steps
Step 1: Check Node.js and npm
Type this and press Enter.
node -vv22.23.1Now check npm.
npm -v10.9.8We used Node.js 22. Track 0 installed Node.js 24, so you may see v24.21.0 and npm 11.19.0.
Both are fine. The number must be 22.12 or higher.
If it is lower, follow the Node.js setup guide.
node -v prints v22.12.0 or a higher number.Step 2: Make the project folder
- Run
mkdir chai-toolsto make a new folder. - Run
cd chai-toolsto go into it. - Run the command below.
npm init -ynpm init makes a package.json file.
-y says "yes" to every question, so npm uses the default answers.
Wrote to C:\...\chai-tools\package.json:
{
"name": "chai-tools",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}The first line shows the full path of the new file.
We shortened our path to C:\... in this lesson. Your path will be your own folder.
chai-tools folder now has a package.json file.Step 3: Add the products file
- Download products.json. It is the same file you used in Track 0.
- Move it into the
chai-toolsfolder. - Open the folder in VS Code with
code .and look at the file.
It holds the 5 Chai Corner products.
Each product is an object with id, title, price, category, inStock and image.
chai-tools folder has package.json and products.json.Step 4: Turn on ES modules
In Track 0 you used import and export in the browser.
Node.js can use them too, but you must say so in package.json.
- Open
package.json. - Add a comma after
"license": "ISC". - Add the line
"type": "module"under it. With npm 11, change"commonjs"to"module"instead. - Save the file.
The end of the file now looks like this:
"license": "ISC",
"type": "module"
}"type": "module" tells Node.js that your .js files use import and export.
} is "type": "module".Step 5: Write a script that reads the file
Create a new file called read-products.js in chai-tools.
Type this code.
import { readFileSync } from "node:fs";
const text = readFileSync("products.json", "utf8");
const products = JSON.parse(text);
console.log(`Chai Corner has ${products.length} products:`);
for (const product of products) {
const status = product.inStock ? "in stock" : "sold out";
console.log(`- ${product.title}: $${product.price} (${status})`);
}Here is what each part does:
node:fsis a module that comes with Node.js.fsmeans "file system". It works with files.readFileSyncreads a whole file and gives it back as text."utf8"says the file is normal text.JSON.parseturns the text into a real array of objects. You met it in Track 0.- The
for...ofloop prints one line for each product.
Now run it.
node read-products.jsChai Corner has 5 products:
- Masala Chai: $12 (in stock)
- Green Tea: $10 (in stock)
- Ginger Honey Tea: $14 (in stock)
- Clay Cup Set: $25 (in stock)
- Tea Strainer: $6 (sold out)Step 6: Install a package
Shopify gives every product a handle.
A handle is the product name in a web address, like masala-chai.
It is like a short name tag for the product.
The slugify package turns any title into a handle.
Install it with this command.
npm install slugify
added 1 package, and audited 2 packages in 3s
found 0 vulnerabilitiesaudited means npm checked the packages for known security problems.
found 0 vulnerabilities means it found none.
Your time, like 3s, will be different.
Open package.json again. npm added a new part at the end:
"type": "module",
"dependencies": {
"slugify": "^1.6.9"
}
}^1.6.9 means "version 1.6.9 or a newer 1.x version".
Look in your folder. npm also made node_modules and package-lock.json.
package.json lists slugify under dependencies, and a node_modules folder exists.Step 7: Use the package
Create a file called make-handles.js.
import { readFileSync } from "node:fs";
import slugify from "slugify";
const products = JSON.parse(readFileSync("products.json", "utf8"));
for (const product of products) {
const handle = slugify(product.title, { lower: true });
console.log(`${product.title} -> ${handle}`);
}You import a package by its name only, like "slugify".
Node.js looks for it in node_modules.
{ lower: true } tells slugify to use small letters.
node make-handles.jsMasala Chai -> masala-chai
Green Tea -> green-tea
Ginger Honey Tea -> ginger-honey-tea
Clay Cup Set -> clay-cup-set
Tea Strainer -> tea-strainerThese match the real handles of the Chai Corner products in a Shopify store.
Step 8: Add npm scripts
Open package.json.
Replace the whole "scripts" part with this:
"scripts": {
"start": "node read-products.js",
"handles": "node make-handles.js"
},Save the file. Now run a script by its name.
npm run handles
> chai-tools@1.0.0 handles
> node make-handles.js
Masala Chai -> masala-chai
Green Tea -> green-tea
Ginger Honey Tea -> ginger-honey-tea
Clay Cup Set -> clay-cup-set
Tea Strainer -> tea-strainernpm first prints the project name, the script name and the real command. Then the script runs.
start is a special name. You can skip the word run.
npm start
> chai-tools@1.0.0 start
> node read-products.js
Chai Corner has 5 products:
- Masala Chai: $12 (in stock)
- Green Tea: $10 (in stock)
- Ginger Honey Tea: $14 (in stock)
- Clay Cup Set: $25 (in stock)
- Tea Strainer: $6 (sold out)npm run handles and npm start both work.Step 9: Rebuild node_modules
node_modules can be very big.
You do not save it in Git. You rebuild it from package.json instead.
- Delete the
node_modulesfolder in VS Code. Right-click it and pick Delete. - Run
node make-handles.js. It fails, because slugify is gone. - Run
npm installwith no package name.
Step 2 prints a long error. The important line is this one:
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'slugify' imported from C:\...\chai-tools\make-handles.jsNow rebuild the folder.
npm install
added 1 package, and audited 2 packages in 2s
found 0 vulnerabilitiesnpm install with no name reads package.json and package-lock.json.
It downloads every dependency again.
Run npm run handles again. It works.
Last, tell Git to skip the folder.
Create a file called .gitignore with this line:
node_modulesnpm run handles works again after npm install.Output
When every step works, your chai-tools folder has:
package.jsonwith"type": "module", two npm scripts andslugifyas a dependency.package-lock.jsonand anode_modulesfolder.products.json,read-products.jsandmake-handles.js.- A
.gitignorefile withnode_modules.
npm start prints the 5 products. npm run handles prints the 5 handles.
Common errors
Cannot use import statement outside a module
You run a script with import, and package.json says "type": "commonjs".
(node:18340) Warning: Failed to load the ES module: C:\...\chai-tools\read-products.js. Make sure to set "type": "module" in the nearest package.json file or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
C:\...\chai-tools\read-products.js:1
import { readFileSync } from "node:fs";
^^^^^^
SyntaxError: Cannot use import statement outside a moduleFix: Set "type": "module" in package.json, as in Step 4.
If there is no "type" line at all, the script runs.
But Node.js prints a long MODULE_TYPELESS_PACKAGE_JSON warning first.
Add "type": "module" to remove it.
Cannot find package 'slugify'
You deleted node_modules, or you forgot to install the package.
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'slugify' imported from C:\...\chai-tools\make-handles.jsFix: Run npm install.
ENOENT: no such file or directory
You ran the script from the wrong folder.
Here we ran node chai-tools/read-products.js from the folder above.
Error: ENOENT: no such file or directory, open 'C:\...\t2a\products.json'ENOENT means "the file is not there".
readFileSync("products.json") looks in the folder where the terminal is, not where the script is.
Fix: Run cd chai-tools first, then run the script again.
Cannot find module
You typed the script name wrong, like read-product.js with no s.
Error: Cannot find module 'C:\...\chai-tools\read-product.js'Fix: Check the spelling. Run ls to see the real file names.
Missing script
You ran an npm script that is not in package.json.
npm error Missing script: "hello"
npm error
npm error To see a list of scripts, run:
npm error npm runFix: Run npm run alone. It lists the scripts you have.
is not valid JSON
products.json has a typo, like an extra comma.
SyntaxError: Unexpected token ',', "[,
{ "id""... is not valid JSON
at JSON.parse (<anonymous>)Fix: Download a fresh products.json, or remove the extra character.
Try it yourself
Practice task
Task: Write a script called stock-report.js.
It reads products.json and prints how many products are in stock and how many are sold out.
For each sold out product, it prints Reorder: and the title.
Add an npm script called report that runs it.
Hints:
- Copy the first two lines of
make-handles.js, but skip the slugify import. - Use
products.filter(...)twice. KeepinStockproducts, then products that are not in stock. - Use
.lengthto count. - Add
"report": "node stock-report.js"to"scripts". Put a comma after the line above it.
Expected result: npm run report prints this:
In stock: 4
Sold out: 1
Reorder: Tea StrainerShow solution
import { readFileSync } from "node:fs";
const products = JSON.parse(readFileSync("products.json", "utf8"));
const inStock = products.filter((product) => product.inStock);
const soldOut = products.filter((product) => !product.inStock);
console.log(`In stock: ${inStock.length}`);
console.log(`Sold out: ${soldOut.length}`);
for (const product of soldOut) {
console.log(`Reorder: ${product.title}`);
} "scripts": {
"start": "node read-products.js",
"handles": "node make-handles.js",
"report": "node stock-report.js"
},npm run report
> chai-tools@1.0.0 report
> node stock-report.js
In stock: 4
Sold out: 1
Reorder: Tea Strainernpm run report prints In stock: 4, Sold out: 1 and Reorder: Tea Strainer.Quick recap
- Node.js runs JavaScript scripts on your computer. Run one with
node file.js. npm init -ymakespackage.json, the ID card of your project.- Add
"type": "module"to useimportandexport. readFileSyncandJSON.parseread a JSON file into objects.npm install <name>adds a dependency. It goes intonode_modules.npm installwith no name rebuildsnode_modules. Never save that folder in Git.- npm scripts are short names for commands. Run them with
npm run <name>. - Shopify CLI needs Node.js 22.12 or higher.