Node.js Basics
Node.js is a JavaScript runtime based on the Chrome V8 engine, used to run JavaScript code on the server. Here are the core concepts and common features of Node.js.
Node.js Introduction
Features
- Single-threaded, non-blocking I/O: Through the event loop and asynchronous I/O, it improves high-concurrency capabilities.
- Modular by design: Uses the CommonJS module specification, making code organization clearer.
- Cross-platform: Supports multiple operating systems (Windows, Linux, macOS).
Use cases
- Build Web services (such as REST APIs).
- Create real-time applications (such as chat, games).
- Scripting tools (such as automation tasks).
- Interacting with the file system.
Core Modules
Node.js provides many built-in modules; here are the commonly used ones:
-
fs(File System module)- Handles files and directories.
const fs = require("fs");// Synchronous file readconst data = fs.readFileSync("example.txt", "utf-8");console.log("File content:", data);// Asynchronous file readfs.readFile("example.txt", "utf-8", (err, data) => {if (err) throw err;console.log("Async file content:", data);}); -
http(HTTP Service module)- Creates an HTTP server.
const http = require("http");const server = http.createServer((req, res) => {res.statusCode = 200;res.setHeader("Content-Type", "text/plain");res.end("Hello, World!");});server.listen(3000, () => {console.log("Server running at http://localhost:3000/");}); -
path(Path handling module)- Handles file paths.
const path = require("path");const filePath = path.join(__dirname, "example.txt");console.log("File path:", filePath); -
os(Operating System information module)- Retrieves information about the operating system.
const os = require("os");console.log("Platform:", os.platform());console.log("Total Memory:", os.totalmem());
npm and Package Management
Purpose of npm
- npm (Node Package Manager) is Node.js’s package management tool, used to install and manage third-party libraries.
Common Commands
-
Initialize a project
npm init -y- Generates a
package.jsonfile.
- Generates a
-
Install a package
npm install express- Installs to the
node_modulesdirectory by default and records it inpackage.json.
- Installs to the
-
Install a global package
npm install -g nodemon- Globally installed packages can be used as commands directly.
-
Remove a package
npm uninstall express
Using Third-Party Modules
Express Example
Express is a popular Node.js web framework, suitable for quickly building web services.
-
Install Express
npm install express -
Create a simple server
const express = require("express");const app = express();app.get("/", (req, res) => {res.send("Hello, Express!");});app.listen(3000, () => {console.log("Express server running at http://localhost:3000/");});
Asynchronous Programming Patterns
The core of Node.js is asynchronous programming; here are several common approaches:
-
Callbacks
const fs = require("fs");fs.readFile("example.txt", "utf-8", (err, data) => {if (err) throw err;console.log("File content:", data);}); -
Promises
const fs = require("fs").promises;fs.readFile("example.txt", "utf-8").then((data) => console.log("File content:", data)).catch((err) => console.error(err)); -
async/await
const fs = require("fs").promises;async function readFileContent() {try {const data = await fs.readFile("example.txt", "utf-8");console.log("File content:", data);} catch (err) {console.error(err);}}readFileContent();
Ok.
If this article helped you, please share it with others!
Some information may be outdated





