package.json and npm init
package.json is the project's passport. It holds the name, the version, the commands for running the project and the list of libraries it depends on. npm, Node.js and code editors all read it. Almost every Node.js project starts by creating this file.
Creating it
The file is created with npm init in the project root, that is, in the blog folder:
npm init -yWithout the -y flag npm asks a few questions (name, version, description); with it, npm fills in the defaults. The file blog/package.json appears in the folder.
Turning on ES modules
The course writes code with import and export. For Node.js to treat .js files as ES modules, package.json needs the field "type": "module". The easiest way to set it is a command:
npm pkg set type=modulenpm pkg set changes a field in package.json without opening an editor.
What is inside
After these two commands the file looks roughly like this:
{
"name": "blog",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}For now three fields matter; the rest can stay as they are.
| Field | Purpose |
|---|---|
name | Project name: lowercase letters, no spaces |
type | module means .js files are ES modules |
scripts | Project commands, run with npm run |
Later, when you install libraries, npm adds the dependencies and devDependencies fields itself — they get their own lesson.
Checking it
Create the file app.js and print the project name by importing package.json as a JSON module:
// app.js
import pkg from './package.json' with { type: 'json' };
console.log(pkg.name, pkg.version);node app.js prints blog 1.0.0. The with { type: 'json' } part tells Node.js that it is importing JSON, not code.
Common mistake
package.json is strict JSON, not a JavaScript object. Comments, single quotes and a comma after the last item are not allowed:
{
"name": "blog",
"type": "module"
}Leave a stray comma and npm and Node.js refuse to read the file with a JSON.parse or EJSONPARSE error. Check the file after editing it by hand, or change fields with npm pkg set.