likes
comments
collection
share

Node.js内置模块(二)

作者站长头像
站长
· 阅读数 1

前言

HTTP模块

HTTP模块是Node.js内置的模块之一,用于创建HTTP服务器和客户端。通过HTTP模块,我们可以轻松地搭建一个简单的Web服务器。下面是一个简单的例子:

const http = require('http');

const server = http.createServer((req, res) => { // req 前端请求, res 后端响应
    res.statusCode = 200; // 设置响应状态码
    res.setHeader('Content-Type', 'text/html'); // 设置响应头

    const { url } = req // url解构赋值
    const query = Object.fromEntries(new URL(url, 'http://localhost').searchParams) // 获取url中的参数

    if(url) {
        if(url === '/home') {
            res.end('<h1>hello home</h1>'); 
        } else if(url.startsWith('/detail') ) { // startsWith以什么开头
            
            if(query.id == 1) {
                res.end('<h1>hello detail111</h1>'); 
            }else if(query.id == 2) {
                res.end('<h1>hello detail22</h1>'); 
            }

        } else {
            res.end('not found')
        }
    }
});

server.listen(3000, () => { // 监听端口
    console.log('server is running on port 3000');
});

这段代码是一个使用Node.js的HTTP模块创建的简单的Web服务器。下面我开始分段解释代码:

const http = require('http');

const server = http.createServer((req, res) => { // req 前端请求, res 后端响应
    res.statusCode = 200; // 设置响应状态码
    res.setHeader('Content-Type', 'text/html'); // 设置响应头

    const { url } = req // url解构赋值
    const query = Object.fromEntries(new URL(url, 'http://localhost').searchParams) // 获取url中的参数

http.createServer方法创建一个HTTP服务器,并传入一个回调函数,该回调函数接收两个参数:req表示请求对象,res表示响应对象。

res.statusCode设置响应状态码为 200 ,表示成功。

res.setHeader设置响应头的Content-Type为text/html,告诉浏览器返回的是HTML类型的内容。

const { url } = req使用解构赋值从请求对象中获取URL。

fromEntries(new URL(url, 'http://localhost').searchParams) 使用URL对象解析URL中的查询参数,并将其转换为一个对象

if(url) {
        if(url === '/home') {
            res.end('<h1>hello home</h1>'); 
        } else if(url.startsWith('/detail') ) { // startsWith以什么开头
            if(query.id == 1) {
                res.end('<h1>hello detail111</h1>'); 
            }else if(query.id == 2) {
                res.end('<h1>hello detail22</h1>'); 
            }
        } else {
            res.end('not found')
        }
    }
server.listen(3000, () => { // 监听端口
    console.log('server is running on port 3000');
});

在这段代码中通过 if(url) 判断URL是否存在。

如果URL是'/home',则返回包含"hello home"的h1标签作为响应体。

如果URL以'/detail'开头,根据查询参数id的不同,返回不同的响应体。

如果URL不匹配上述条件,则返回"not found"作为响应体。

server.listen(3000, ...)开始监听3000端口,当服务器成功运行后,执行回调函数打印提示信息。

HTTPS模块

HTTPS模块是在HTTP模块的基础上增加了SSL/TLS加密功能,用于创建安全的HTTPS服务器。使用HTTPS模块需要配置证书和私钥。下面是一个简单的HTTPS服务器的例子:

const https = require('https')

const req = https.get(
   'https://www.fastmock.site/mock/39ac87de3060aa2bb2ba20a0ff375c81/cat-movie/mostLike',
    {
        headers: {
            'Content-Type': 'application/json'
        }
    }
)

req.on('response', (res) => {
    let content = ''
    res.on('data', (chunk) => {
        content += chunk
    })
    res.on('end', () => {
        console.log(content)
    })
})

const req = https.get(...); 使用https.get方法创建一个HTTPS GET请求

headers: { 'Content-Type': 'application/json' } 通过headers选项设置了请求头,指定了 Content-Type 为 application/json 。

req.on('response', (res) => {对请求的响应进行监听,当收到响应时执行回调函数。

let content = '';: 定义一个变量 content 用于存储响应内容。

res.on('data', (chunk) => { content += chunk; });当接收到数据时,将数据块拼接到 content 变量中。

res.on('end', () => { console.log(content); });当响应结束时,输出拼接好的 content 变量,即完整的响应内容。

Util模块

Util模块提供了一些实用工具函数,用于简化开发过程。其中,最常用的是util.promisify,用于将基于回调的异步函数转换为Promise风格的函数。下面是一个例子:

const util = require('util')

const obj = {
    a: 1,
    b: {
        c: 2,
        d: [3, 4, 5],
        e: () => {
            console.log(6);
        }
    }
}

console.log(util.inspect(obj), { depth: 1 });  // inspect() 方法返回 obj 的字符串表示形式

console.log(util.format('%s:%s','foo', 'bar'));
console.log(util.format('%d + %d = %d', 1, 2, 3));
console.log(util.format('hello %j', {name: 'tom'}));

Node.js内置模块(二)

使用util.inspect方法将对象转换为字符串,以便在控制台中打印。第二个参数 { depth: 1 } 指定深度为1,以避免过度展开对象的层次结构。

使用util.format方法根据格式字符串返回格式化的字符串。

感谢您的阅读,一键三连精彩继续