JavaScript + Node.js track

Lesson 24 · Part 7: Node.js Fundamentals

The Node Environment

Running `node`, `process`, `fs` and CommonJS vs ESM

Part 7: Node.js Fundamentals2 min readFree lesson

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 fs module.
  • 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

  1. Use browser API (window, document) in Node.
  2. Use require on ESM (and vice versa).
  3. Omit ./ in the relative path.
  4. I couldn't find the file created with fs.writeFileSync because I didn't know it was created in a different working directory.
  5. 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.

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/01_hello_node.jsJavaScript
/**
 *Run your first node
 *Run: node 01_hello_node.js
 */
console.log('Hello, Node!');
console.log('Node version:', process.version);
console.log('Platform:', process.platform);
src/02_process.jsJavaScript
/**
 *process.argv and process.env
 *Execution example: node 02_process.js apple 5
 */
const [, , fruit, countStr] = process.argv;
const count = Number(countStr ?? 1);

console.log(`Arguments: ${fruit} × ${count}`);
console.log('full argv:', process.argv);
console.log('HOME environment variable:', process.env.HOME ?? process.env.USERPROFILE);
src/03_fs_basic.jsJavaScript
/**
 *Write and read text files with fs
 */
const { writeFileSync, readFileSync, existsSync } = require('node:fs');

const path = 'hello.txt';
writeFileSync(path, 'Hello Node\nSecond line');

if (existsSync(path)) {
  const text = readFileSync(path, 'utf-8');
  console.log('File contents:');
  console.log(text);
}
src/04_commonjs_esm.mjsJavaScript
/**
 *ESM style — .mjs extension
 *Comparative comments with CommonJS included
 */
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';

//In CommonJS, __filename and __dirname are provided by default, but
//You have to make it yourself in ESM
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

console.log('This file:', __filename);
console.log('This directory:', __dirname);

// CommonJS:
//   const { readFileSync } = require('node:fs');
//   module.exports = { ... };
//
// ESM:
//   import { readFileSync } from 'node:fs';
//   export { ... };

export const hello = () => 'Hello from ESM';
console.log(hello());

Assignment

Assignment 1 (CommonJS)

Add two numbers received from the command line and print them. node homework_01.js 3 5 → Total: 8

Assignment 2 (ESM)

Append the string received from the command line one line at a time to the note.txt file. After running node homework_02.mjs "Today's Memo", check the file contents.

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

homework_01.jsJavaScript
/**
 *Task 1: Adding two command line arguments (CommonJS)
 *Run: node homework_01.js 3 5
 */
const [, , aStr, bStr] = process.argv;
const a = Number(aStr);
const b = Number(bStr);

if (Number.isNaN(a) || Number.isNaN(b)) {
  console.error('Please enter two numbers.');
  process.exit(1);
}

console.log(`Sum: ${a + b}`);
homework_02.mjsJavaScript
/**
 *Task 2: Add a note to note.txt (ESM)
 *Run: node homework_02.mjs "Today's Note"
 */
import { appendFileSync, readFileSync, existsSync } from 'node:fs';

const text = process.argv[2];
if (!text) {
  console.error('Please provide the string to be added as an argument.');
  process.exit(1);
}

const path = 'note.txt';
appendFileSync(path, text + '\n');

console.log('--- Current note.txt ---');
console.log(existsSync(path) ? readFileSync(path, 'utf-8') : '(none)');

Learn this lesson with a mentor

Work through the JavaScript + Node.js track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now