Level: Advanced | Player: 23_Module_ESM
Learning Objectives
- You can run JS files with Node.
- Use
process.argv,process.env. - You can read and write files with the
fsmodule. - Know the difference between CommonJS and ESM module systems.
1. What is Node?
A runtime that executes JS outside the browser. Used for servers, CLI, build tools, etc.
Verify installation:
node -v
Run:
node 01_hello_node.js
2. process — Arguments and environment variables
console.log(process.argv); //['node path', 'script path', ...additional arguments]
console.log(process.env.HOME);
node 02_process.js apple 5
3. fs — file system
import { readFileSync, writeFileSync } from 'node:fs';
writeFileSync('hello.txt', 'Hello Node');
const text = readFileSync('hello.txt', 'utf-8');
console.log(text);
There is also an asynchronous version (readFile, promises API).
4. CommonJS vs ESM
Two module systems coexist in Node.
| Item | CommonJS | ESM |
|---|---|---|
| file extension | .js (default) |
.mjs or "type":"module" |
| Export | module.exports = ... |
export |
| import | require('./x') |
import |
| loading | motivation | asynchronous |
// CommonJS (legacy.cjs)
module.exports = { hi: () => 'hi' };
const { hi } = require('./legacy');
// ESM (modern.mjs)
export const hi = () => 'hi';
import { hi } from './modern.mjs';
ESM is recommended for new codes.
Core example
| file | Contents covered |
|---|---|
| 01_hello_node.js | First steps in running node |
| 02_process.js | Using argv/env |
| 03_fs_basic.js | File read/write |
| 04_commonjs_esm.mjs | Comparison of two modular systems |
⚠️ Common Mistakes
- Use browser API (
window,document) in Node. - Use
requireon ESM (and vice versa). - Omit
./in the relative path. - I couldn't find the file created with
fs.writeFileSyncbecause I didn't know it was created in a different working directory. - Hard-code environment variables into your code.
❓ Frequently Asked Questions (FAQ)
Q1. Which Node version should I use? A. The latest LTS (even major) is recommended.
Q2. What is the .env file? A. --env-file package for Node 20+, dotenv package for others.
Q3. What is the working directory? A. Check with process.cwd(). This is usually the location where the command was executed.