Node.js Basics
Understand the core concepts of Node.js including the global object, modules, the require function, and how to read and write files.
In this episode, we'll dive into the fundamental building blocks of Node.js — the global object, modules, and file system operations.
The Global Object
In the browser, the global object is window. In Node.js, it's global. Some commonly available globals include:
console— For logging outputsetTimeout/setInterval— For timing operations__dirname— The directory path of the current file__filename— The full file path of the current file
console.log(__dirname); // e.g., /Users/you/project
console.log(__filename); // e.g., /Users/you/project/app.js
Modules and require()
Node.js uses a module system to organize code. Every file is treated as a separate module. You export functionality from one file and import it into another using require():
// utils.js
const greet = (name) => `Hello, ${name}!`;
const add = (a, b) => a + b;
module.exports = { greet, add };
// app.js
const { greet, add } = require('./utils');
console.log(greet('World')); // Hello, World!
console.log(add(5, 3)); // 8
Built-in Modules
Node.js comes with powerful built-in modules that you don't need to install:
os— Operating system infofs— File system operationspath— File path utilitieshttp— Create HTTP serversevents— Event-driven programming
Reading and Writing Files
The fs (file system) module lets you interact with files:
const fs = require('fs');
// Reading a file (async)
fs.readFile('./hello.txt', 'utf8', (err, data) => {
if (err) console.log(err);
console.log(data);
});
// Writing a file (async)
fs.writeFile('./output.txt', 'Hello from Node!', () => {
console.log('File written successfully');
});
Always prefer asynchronous methods — they don't block the thread while waiting for I/O to complete.