mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4
245 words
1 minute
Getting Started with Node.js
2024-11-16

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#

  1. Single-threaded, non-blocking I/O: Through the event loop and asynchronous I/O, it improves high-concurrency capabilities.
  2. Modular by design: Uses the CommonJS module specification, making code organization clearer.
  3. 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:

  1. fs (File System module)

    • Handles files and directories.
    const fs = require("fs");
    // Synchronous file read
    const data = fs.readFileSync("example.txt", "utf-8");
    console.log("File content:", data);
    // Asynchronous file read
    fs.readFile("example.txt", "utf-8", (err, data) => {
    if (err) throw err;
    console.log("Async file content:", data);
    });
  2. 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/");
    });
  3. path (Path handling module)

    • Handles file paths.
    const path = require("path");
    const filePath = path.join(__dirname, "example.txt");
    console.log("File path:", filePath);
  4. 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#

  1. Initialize a project

    npm init -y
    • Generates a package.json file.
  2. Install a package

    npm install express
    • Installs to the node_modules directory by default and records it in package.json.
  3. Install a global package

    npm install -g nodemon
    • Globally installed packages can be used as commands directly.
  4. 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.

  1. Install Express

    npm install express
  2. 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:

  1. Callbacks

    const fs = require("fs");
    fs.readFile("example.txt", "utf-8", (err, data) => {
    if (err) throw err;
    console.log("File content:", data);
    });
  2. Promises

    const fs = require("fs").promises;
    fs.readFile("example.txt", "utf-8")
    .then((data) => console.log("File content:", data))
    .catch((err) => console.error(err));
  3. 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.

Share

If this article helped you, please share it with others!

Getting Started with Node.js
https://dreaife.tokyo/en/posts/nodejs-basics/
Author
dreaife
Published at
2024-11-16
License
CC BY-NC-SA 4.0

Some information may be outdated

Related Posts Smart
1
Bidding Platform Based on Nest.js and Angular, with Jest Tests and CI/CD
BACKEND This project is a bidding platform built with Nest.js and Angular, providing features such as user registration, project management, and bid management. It uses PostgreSQL as the database and Swagger to generate API documentation. The backend implements secure authentication with AWS Cognito, while the frontend provides a user-friendly interface for project display and bid management. The project uses Jest for testing to ensure code quality and GitHub Actions for continuous integration and deployment.
2
Getting Started with TypeScript
FRONTEND TypeScript basics include the type system, interfaces, classes, decorators, and more. It supports many primitive types such as number, string, and boolean, and also provides features such as type annotations, generics, union types, and type aliases. Decorators are used to apply metadata to classes and methods, while modules and namespaces help organize code.
3
Getting Started with Angular
FRONTEND This beginner guide to Angular covers project creation, Angular CLI commands, component and module structure, data binding, directives, services and dependency injection, routing and navigation, form handling, the HTTP client, RxJS, state management, performance optimization, PWA support, and internationalization. It includes detailed command examples and code structure references to help developers get started quickly.
4
Getting Started with Elasticsearch
middle-side Elasticsearch is a powerful open-source search engine built on Lucene and is commonly used for data storage, search, and analytics. Core concepts include inverted indexes, documents and fields, and indexes and mappings. Comparisons with MySQL show different strengths in data processing. Installation and usage involve index creation, document operations, and REST API queries. Aggregations support statistical analysis, while autocomplete and data synchronization improve user experience and data consistency. Cluster management ensures high availability and data security.
5
Getting Started with Redis
middle-side Redis is an in-memory key-value NoSQL database with low latency and rich data structure support. Compared with traditional relational databases, Redis does not strictly constrain data formats and supports horizontal scaling. Common commands include key-value operations, hash operations, list operations, and set operations. Jedis and Spring Data Redis are the main Java clients for interacting with Redis, providing convenient APIs and connection pool management. Data serialization can be optimized with custom strategies to reduce memory usage.

Table of Contents