Backend Development 31 min read

Node.js Quick Start Tutorial: Environment, Global Objects, Modules, CLI, npm, and Event Handling

This tutorial provides a comprehensive introduction to Node.js, covering its runtime environment, core global objects, module system, command‑line interface development, npm package management, script automation, and event handling with practical code examples and explanations for front‑end engineers transitioning to back‑end development.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Node.js Quick Start Tutorial: Environment, Global Objects, Modules, CLI, npm, and Event Handling

Introduction to Node.js

Node.js is a JavaScript runtime built on the V8 engine, allowing JavaScript to run outside the browser. It offers asynchronous, event‑driven, non‑blocking execution, which makes it ideal for high‑performance server‑side applications.

What is Node?

Node.js provides a runtime environment separate from the browser. While browsers expose window and document , Node exposes its own global objects such as process , __dirname , and __filename .

Prerequisites

Basic knowledge of JavaScript.

Node.js installed and an editor configured.

Understanding of relative and absolute paths.

Learning Goals

Understand differences between browser JavaScript and Node.js.

Explore Node.js global objects.

Learn module import/export with require , exports , and module .

Write simple command‑line applications.

Use npm packages such as commander and ora .

Set up npm scripts for development workflow.

Running Node Code

You can run Node code interactively in the REPL or by saving it to a .js file and executing it with node :

$ node -v
$ node
> 1 + 2
3

Writing a Simple Script

Create timer.js with the following content:

console.log('Hello World!');

Execute it:

$ node timer.js
Hello World!

Node Global Objects

The most important global object is process , which provides information about the current process:

process.pid – Process ID.

process.env – Environment variables.

process.argv – Command‑line arguments.

process.platform – Operating system platform.

Node‑specific globals include process , Buffer , __dirname , and __filename . Unlike browsers, Node does not have window or document .

Node Module System

Node implements the CommonJS module specification. Modules can be core (built‑in) or file‑based. Use require to import and exports or module.exports to export.

require

Three ways to specify a module identifier:

Core or third‑party module name, e.g., os or express .

Relative path, e.g., ./utils .

Absolute path (not recommended), e.g., /home/user/project/utils .

// Import core and third‑party modules
const os = require('os');
const express = require('express');

// Import a local module
const utils = require('./utils');

exports

Export values from a module by attaching them to exports :

// myModule.js
function add(a, b) {
  return a + b;
}
exports.add = add;

Or export a single value by assigning to module.exports :

// myModule.js
module.exports = add;

module

The module object contains metadata such as id , filename , exports , parent , children , and paths (the search list for modules).

Practical Example: Timer Application

Create info.js to print system information:

const os = require('os');
function printProgramInfo() {
  console.log('Current user', os.userInfo().username);
  console.log('Process ID', process.pid);
  console.log('Script path', __filename);
}
module.exports = printProgramInfo;

Create datetime.js to return the current time:

function getCurrentTime() {
  const time = new Date();
  return time.toLocaleString();
}
exports.getCurrentTime = getCurrentTime;

Update timer.js to use these modules and accept command‑line arguments:

const printProgramInfo = require('./info');
const datetime = require('./datetime');
const waitTime = Number(process.argv[3]); // --time value
const message = process.argv[5]; // --message value
setTimeout(() => {
  console.log(message);
}, waitTime * 1000);
printProgramInfo();
console.log('Current time', datetime.getCurrentTime());

Command‑Line Development

Use process.argv to read arguments, but parsing manually is error‑prone. The commander package simplifies this:

const program = require('commander');
program
  .option('-t, --time
', 'Wait time in seconds', 3)
  .option('-m, --message
', 'Message to display', 'Hello World')
  .parse(process.argv);

Combine with ora for a loading spinner:

const ora = require('ora');
const spinner = ora('Loading...').start();
setTimeout(() => {
  spinner.stop();
  console.log(program.message);
}, program.time * 1000);

npm: Package Management

Initialize a project with npm init , which creates package.json . Install dependencies:

$ npm install commander ora

The dependencies field records direct dependencies, while devDependencies holds development‑only tools such as eslint :

$ npm install eslint --save-dev

Example package.json excerpt:

{
  "name": "timer",
  "version": "1.0.0",
  "main": "timer.js",
  "scripts": {
    "lint": "eslint **/*.js",
    "start": "node timer.js -m 'Ready' -t 3"
  },
  "dependencies": {
    "commander": "^4.0.1",
    "ora": "^4.0.3"
  },
  "devDependencies": {
    "eslint": "^6.7.2"
  }
}

Run scripts with npm start or npm run lint .

Event Handling with EventEmitter

Node’s event system is based on the events module’s EventEmitter class. Use on to listen and emit to trigger events:

const EventEmitter = require('events').EventEmitter;
const emitter = new EventEmitter();
emitter.on('connect', username => {
  console.log(`${username} connected`);
});
emitter.emit('connect', 'A bird');

The global process object also inherits from EventEmitter . Listening to the exit event ensures cleanup logic runs regardless of how the process terminates:

process.on('exit', () => {
  console.log('See you next time~');
});

This tutorial concludes with a full‑featured Node.js starter project that demonstrates environment setup, core concepts, modular code organization, CLI argument parsing, npm workflow, and basic event handling.

CLIJavaScriptbackend developmentNode.jsnpmModulesEventEmitter
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.