1. Node.js basics: npm, packages and scripts

Aap kis language mein padhna chahoge?

Which language do you want to learn in?

Code aur technical words English mein hi rahenge. Aap baad mein bhi language badal sakte ho.

Lesson 1

Node.js basics: npm, packages and scripts

Beginner 60 minutes

You need before starting

  • Track 0, all lessons. You need the terminal, JSON, array methods and ES modules.
  • Node.js 22.12 or higher. The Node.js 24 LTS from Track 0 is fine.
  • VS Code with its terminal

What you will learn

  • Make a new Node.js project with npm init.
  • Read what package.json says about your project.
  • Write a script that reads the Chai Corner products.json file.
  • 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.json lists 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

  1. Open VS Code.
  2. Open the terminal with Terminal > New Terminal.
  3. 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.

Terminal
node -v
Output
v22.23.1

Now check npm.

Terminal
npm -v
Output
10.9.8

We 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.

Check: node -v prints v22.12.0 or a higher number.

Step 2: Make the project folder

  1. Run mkdir chai-tools to make a new folder.
  2. Run cd chai-tools to go into it.
  3. Run the command below.
Terminal
npm init -y

npm init makes a package.json file. -y says "yes" to every question, so npm uses the default answers.

Output
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.

Check: Your chai-tools folder now has a package.json file.

Step 3: Add the products file

  1. Download products.json. It is the same file you used in Track 0.
  2. Move it into the chai-tools folder.
  3. 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.

Check: The 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.

  1. Open package.json.
  2. Add a comma after "license": "ISC".
  3. Add the line "type": "module" under it. With npm 11, change "commonjs" to "module" instead.
  4. Save the file.

The end of the file now looks like this:

package.json
  "license": "ISC",
  "type": "module"
}

"type": "module" tells Node.js that your .js files use import and export.

Check: The last line before } 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.

read-products.js
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:fs is a module that comes with Node.js. fs means "file system". It works with files.
  • readFileSync reads a whole file and gives it back as text. "utf8" says the file is normal text.
  • JSON.parse turns the text into a real array of objects. You met it in Track 0.
  • The for...of loop prints one line for each product.

Now run it.

Terminal
node read-products.js
Output
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)
Check: You see all 5 products, and Tea Strainer says 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.

Terminal
npm install slugify
Output

added 1 package, and audited 2 packages in 3s

found 0 vulnerabilities

audited 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:

package.json
  "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.

Check: package.json lists slugify under dependencies, and a node_modules folder exists.

Step 7: Use the package

Create a file called make-handles.js.

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.

Terminal
node make-handles.js
Output
Masala Chai -> masala-chai
Green Tea -> green-tea
Ginger Honey Tea -> ginger-honey-tea
Clay Cup Set -> clay-cup-set
Tea Strainer -> tea-strainer

These match the real handles of the Chai Corner products in a Shopify store.

Check: Each title has a handle in small letters with dashes.

Step 8: Add npm scripts

Open package.json. Replace the whole "scripts" part with this:

package.json
  "scripts": {
    "start": "node read-products.js",
    "handles": "node make-handles.js"
  },

Save the file. Now run a script by its name.

Terminal
npm run handles
Output

> 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-strainer

npm 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.

Terminal
npm start
Output

> 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)
Check: 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.

  1. Delete the node_modules folder in VS Code. Right-click it and pick Delete.
  2. Run node make-handles.js. It fails, because slugify is gone.
  3. Run npm install with no package name.

Step 2 prints a long error. The important line is this one:

Output
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'slugify' imported from C:\...\chai-tools\make-handles.js

Now rebuild the folder.

Terminal
npm install
Output

added 1 package, and audited 2 packages in 2s

found 0 vulnerabilities

npm 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:

.gitignore
node_modules
Check: npm run handles works again after npm install.

Output

When every step works, your chai-tools folder has:

  • package.json with "type": "module", two npm scripts and slugify as a dependency.
  • package-lock.json and a node_modules folder.
  • products.json, read-products.js and make-handles.js.
  • A .gitignore file with node_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".

Output
(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 module

Fix: 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.

Output
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'slugify' imported from C:\...\chai-tools\make-handles.js

Fix: 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.

Output
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.

Output
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.

Output
npm error Missing script: "hello"
npm error
npm error To see a list of scripts, run:
npm error   npm run

Fix: Run npm run alone. It lists the scripts you have.

is not valid JSON

products.json has a typo, like an extra comma.

Output
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. Keep inStock products, then products that are not in stock.
  • Use .length to count.
  • Add "report": "node stock-report.js" to "scripts". Put a comma after the line above it.

Expected result: npm run report prints this:

Output
In stock: 4
Sold out: 1
Reorder: Tea Strainer
Show solution
stock-report.js
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}`);
}
package.json
  "scripts": {
    "start": "node read-products.js",
    "handles": "node make-handles.js",
    "report": "node stock-report.js"
  },
Terminal
npm run report
Output

> chai-tools@1.0.0 report
> node stock-report.js

In stock: 4
Sold out: 1
Reorder: Tea Strainer
Check: npm 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 -y makes package.json, the ID card of your project.
  • Add "type": "module" to use import and export.
  • readFileSync and JSON.parse read a JSON file into objects.
  • npm install <name> adds a dependency. It goes into node_modules.
  • npm install with no name rebuilds node_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.