Node.js 网络
Node.js 提供了强大的网络模块,使得你能够轻松创建服务器和处理网络请求。以下是一些关于 Node.js 网络编程的基本概念和用法:1. 创建 HTTP 服务器:使用 http 模块可以轻松创建一个简单的 HTTP 服务器。const http = require('http');const server = http.createServer((req, res) => { // 处理请求 res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello, World!\n');});const PORT = 3000;const HOST = '127.0.0.1';server.listen(PORT, HOST, () => { console.log(`Server running at http://${HOST}:${PORT}/`);});2. 处理 HTTP 请求:HTTP 服务器通过监听请求事...
Node.js 流
在 Node.js 中,流(Streams)是一种处理输入输出的抽象接口,用于有效地读取或写入大量数据。流可以分为可读流(Readable)、可写流(Writable)、双工流(Duplex),以及转换流(Transform)等不同类型。以下是一些关于 Node.js 流的基本概念和用法:1. 可读流(Readable Stream):可读流用于从数据源读取数据。const fs = require('fs');// 创建可读流const readableStream = fs.createReadStream('example.txt', 'utf-8');// 监听 'data' 事件,处理流中的数据readableStream.on('data', (chunk) => { console.log('Received chunk:', chunk);});// 监听 'end' 事件,表示数据读取完毕readableStream.on('end'...
Node.js 加密
在 Node.js 中,你可以使用内置的 crypto 模块来进行加密操作。crypto 模块提供了各种加密算法和功能,包括哈希、HMAC(Hash-based Message Authentication Code)、加密和解密等。以下是一些基本的加密操作示例:1. 哈希算法:使用哈希算法可以将任意长度的数据映射为固定长度的哈希值。常见的哈希算法包括 MD5、SHA-256 等。const crypto = require('crypto');const data = 'Hello, World!';// 使用 MD5 哈希算法const md5Hash = crypto.createHash('md5').update(data).digest('hex');console.log('MD5 Hash:', md5Hash);// 使用 SHA-256 哈希算法const sha256Hash = crypto.createHash('sha256').update(data).dige...
Node.js 模块
Node.js 使用模块来组织和管理代码。在 Node.js 中,模块是 JavaScript 文件,它封装了一组相关的功能,并且可以被其他文件引入和重复使用。以下是一些关于 Node.js 模块的基本信息:1. 创建模块: 你可以通过在一个文件中编写代码,然后使用 module.exports 导出需要在其他文件中访问的内容。例如: // exampleModule.js const greeting = "Hello, "; function greet(name) { console.log(greeting + name); } module.exports = greet;2. 引入模块: 在其他文件中,你可以使用 require 来引入模块,并且得到导出的内容。例如: // main.js const greet = require('./exampleModule'); greet('World');3. 内置模块: Node.js 提供了许多内置模块,如 fs(文件系...
Node.js 控制台
在 Node.js 中,console 模块提供了一系列用于在控制台中打印输出的方法。这些方法对于调试、记录日志以及与开发人员进行交互都非常有用。以下是一些常见的 console 方法:1. console.log(): 打印普通日志消息。 console.log('Hello, World!');2. console.error(): 打印错误消息。 console.error('This is an error message.');3. console.warn(): 打印警告消息。 console.warn('This is a warning message.');4. console.info(): 打印信息性消息。 console.info('This is an informational message.');5. console.dir(): 使用类似于 util.inspect() 的方式打印对象的内容。 const myObject = { name: 'John'...
Node.js HTTPS
在 Node.js 中,https 模块提供了创建和处理 HTTPS 服务器的功能。使用 HTTPS 服务器可以保障数据在传输过程中的安全性。以下是一个简单的使用 https 模块创建 HTTPS 服务器的示例:const https = require('https');const fs = require('fs');// 读取 SSL 证书和私钥文件const options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('public-cert.pem')};// 创建 HTTPS 服务器const server = https.createServer(options, (req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello, secure world!\n'...
Node.js 集群
在 Node.js 中,可以使用集群(cluster)模块来创建多个进程,从而充分利用多核系统的性能。集群模块使得一个主进程(master)可以创建多个子进程(workers),每个子进程都可以独立运行 Node.js 应用程序的实例。以下是一个基本的 Node.js 集群示例:const cluster = require('cluster');const os = require('os');// 如果是主进程if (cluster.isMaster) { console.log(`Master ${process.pid} is running`); // 获取 CPU 核心数 const numCPUs = os.cpus().length; // 创建子进程 for (let i = 0; i < numCPUs; i++) { cluster.fork(); } // 监听子进程退出事件,如果有子进程退出,则创建一个新的子进程 cluster.on('exit', (worker, code, si...
Node.js HTTP
在 Node.js 中,http 模块提供了创建 HTTP 服务器和客户端的功能。以下是一些关于使用 http 模块的基本示例:1. 创建简单的 HTTP 服务器: const http = require('http'); // 创建 HTTP 服务器 const server = http.createServer((req, res) => { // 处理请求 res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello, World!\n'); }); // 指定服务器监听的端口 const port = 3000; server.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); }); 在这个例子中,通过 http.createServer 创建了一个简...
Node.js REPL
REPL(Read-Eval-Print Loop)是 Node.js 中的一个交互式运行环境,允许你在终端中直接执行 JavaScript 代码并查看结果。你可以通过在终端中键入 node 命令启动 REPL。以下是一些 REPL 的基本用法:1. 启动 REPL: 打开终端并键入 node 命令: node 进入 REPL 后,你将看到 > 提示符,可以在此输入 JavaScript 代码。2. 执行代码: 在 REPL 中,你可以直接输入 JavaScript 代码并按 Enter 键执行。例如: > const message = 'Hello, REPL!'; > console.log(message); 这将输出 'Hello, REPL!'。3. 多行输入: 如果你要输入多行代码块,可以使用 ... 连续输入。例如: > function add(a, b) { ... return a + b; ... } 输入完最后一行后按两次 Enter 键以执行。4. 特...
Node.js 子进程
在 Node.js 中,子进程模块 child_process 允许你生成和与子进程进行交互。这对于执行外部命令、脚本或长时间运行的任务是很有用的。以下是一些 child_process 模块的基本用法示例:1. 执行外部命令: const { exec } = require('child_process'); // 执行 shell 命令 exec('ls -l', (error, stdout, stderr) => { if (error) { console.error(`Error: ${error.message}`); return; } console.log(`stdout: ${stdout}`); console.error(`stderr: ${stderr}`); }); 在上述示例中,exec 函数用于执行一个 shell 命令。回调函数将在命令执行完成后被调用,可以获取标准输出、标准错误和错误信息。2. 生成子进程: const { sp...
Node.js 逐行读取
在 Node.js 中,你可以使用 readline 模块来逐行读取文件或者从标准输入流中逐行读取数据。下面是一个简单的示例,演示如何使用 readline 模块逐行读取文件:1. 逐行读取文件: const readline = require('readline'); const fs = require('fs'); // 创建可读流 const fileStream = fs.createReadStream('example.txt'); // 创建逐行读取的接口 const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity // 用于处理换行符 }); // 逐行读取 rl.on('line', (line) => { console.log(`Line from file: ${line}`); }); // 文件读取完成事件 rl.on(&...
Node.js C/C++ 插件
Node.js 允许通过 C/C++ 编写插件,这样你就可以在 Node.js 中使用底层的系统功能或者已有的 C/C++ 库。插件的编写需要使用 Node.js 提供的 C/C++ API。以下是一个简单的例子,演示了如何编写一个使用 C++ 编写的简单插件,并在 Node.js 中调用它。1. 创建 addon.cpp 文件: #include <node.h> using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; // 定义插件函数,将两个数字相加 void Add(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); // 获取传入的参数 double value = args[0]->Nu...
Node.js Query Strings
在 Node.js 中,querystring 模块用于处理 URL 查询字符串。查询字符串是 URL 中的参数部分,通常以 key=value 形式出现,多个参数之间使用 & 连接。querystring 模块提供了将查询字符串解析为对象、将对象序列化为查询字符串的功能。以下是一些 querystring 模块的基本用法示例:1. 解析查询字符串: const querystring = require('querystring'); const queryString = 'name=John&age=30&city=New York'; // 将查询字符串解析为对象 const parsedObject = querystring.parse(queryString); console.log(parsedObject); // 输出: { name: 'John', age: '30', city: 'New York' }2. 序列化对象...
Node.js Buffer
在 Node.js 中,Buffer 是一个用于处理二进制数据的类。Buffer 类是 Node.js 核心模块之一,用于处理文件、网络流、编码和解码等场景。以下是关于 Buffer 的基本信息和用法:1. 创建 Buffer: 你可以使用多种方式创建 Buffer,包括分配指定大小的 Buffer、通过字符串创建 Buffer,以及通过其他数据类型创建 Buffer。以下是一些常见的创建 Buffer 的方式: // 分配一个大小为 10 字节的 Buffer const buffer1 = Buffer.alloc(10); // 通过字符串创建 Buffer const buffer2 = Buffer.from('Hello, Node.js!'); // 通过数组创建 Buffer const buffer3 = Buffer.from([1, 2, 3, 4, 5]); console.log(buffer1, buffer2, buffer3);2. 读取和写入数据: 可以通过索引读取和写入 Buffer 中的数据...
Node.js Punycode
在 Node.js 中,punycode 模块提供了对[Punycode](https://en.wikipedia.org/wiki/Punycode)编码和解码的支持。Punycode 是一种用于处理国际化域名的编码方案,允许将 Unicode 域名转换为 ASCII 字符串,以便在标准的 DNS 系统中使用。以下是一个简单的示例,演示了如何在 Node.js 中使用 punycode 模块进行编码和解码:const punycode = require('punycode');// 编码(Unicode to ASCII)const encoded = punycode.encode('你好.world');console.log('Encoded: ' + encoded); // 输出: 'xn--6qqa088eba.world'// 解码(ASCII to Unicode)const decoded = punycode.decode('xn--6qqa088eba.world');cons...
Node.js 事件
在 Node.js 中,事件是一个核心概念,用于处理异步操作。Node.js 的事件系统建立在观察者模式的基础上。以下是关于 Node.js 事件的基本信息:1. EventEmitter 类: 在 Node.js 中,events 模块提供了 EventEmitter 类,该类用于实现事件的发布和订阅。EventEmitter 的实例可以触发事件,也可以监听事件。2. 基本使用示例: 下面是一个简单的示例,演示了如何使用 EventEmitter: const EventEmitter = require('events'); // 创建一个事件发射器实例 const myEmitter = new EventEmitter(); // 监听 'event' 事件 myEmitter.on('event', () => { console.log('Event occurred!'); }); // 触发 'event' 事件 myEmitt...
Node.js 断言测试
在Node.js中,你可以使用内置的assert模块进行断言测试。断言是用于在代码中检查条件是否成立的方法,通常在开发和测试阶段用于验证代码的正确性。以下是一个简单的Node.js断言测试的示例:const assert = require('assert');// 示例函数,将两个数字相加function add(a, b) { return a + b;}// 进行断言测试assert.strictEqual(add(2, 3), 5, 'Expected add(2, 3) to equal 5');assert.strictEqual(add(-1, 1), 0, 'Expected add(-1, 1) to equal 0');assert.strictEqual(add(0, 0), 0, 'Expected add(0, 0) to equal 0');// 如果所有断言通过,输出成功信息console.log('All assertions passed!');在这个例子中,我们使用as...
Node.js 示例
以下是一个简单的Node.js示例,演示了如何创建一个HTTP服务器并监听端口。请确保你已经安装了Node.js并创建了一个空的JavaScript文件(例如,app.js)来运行以下代码:// 引入核心模块 httpconst http = require('http');// 创建 HTTP 服务器并定义请求处理函数const server = http.createServer((req, res) => { // 设置响应头 res.writeHead(200, {'Content-Type': 'text/plain'}); // 发送响应内容 res.end('Hello, Node.js!\n');});// 指定服务器监听的端口号const port = 3000;// 服务器开始监听指定端口server.listen(port, () => { console.log(`Server running at http://localhost:${port}/`);});这个简单的示例创...
Node.js 连接 MongoDB
在 Node.js 中连接 MongoDB,你可以使用 mongodb 驱动程序。以下是基本的步骤:1. 安装 MongoDB 驱动程序: 使用 npm 安装 mongodb 驱动程序。 npm install mongodb2. 在代码中使用 MongoDB 驱动程序: 创建一个 Node.js 文件,然后使用以下代码连接到 MongoDB 数据库: const { MongoClient } = require('mongodb'); // MongoDB 连接字符串,替换为你的实际连接字符串 const uri = 'mongodb://your_username:your_password@your_host:your_port/your_database'; // 创建 MongoDB 客户端 const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); // 连接到 MongoDB cl...
Node.js 连接 MySQL
要在 Node.js 中连接 MySQL 数据库,你可以使用 mysql 模块。以下是基本的步骤:1. 安装 MySQL 模块: 使用 npm 安装 mysql 模块。 npm install mysql2. 在代码中使用 MySQL 模块: 创建一个 Node.js 文件,然后使用以下代码连接到 MySQL 数据库: const mysql = require('mysql'); // 创建数据库连接 const connection = mysql.createConnection({ host: 'your_mysql_host', user: 'your_mysql_user', password: 'your_mysql_password', database: 'your_mysql_database' }); // 连接到数据库 connection.connect((err) => { if (err) { ...