Node.js 网络与路径模块
HTTP 模块
js
const http = require('http')const http = require('http')创建 HTTP 服务
js
const server = http.createServer((req, res) => {
// req — 请求对象
console.log(req.url) // 请求路径
console.log(req.method) // 请求方法
console.log(req.headers) // 请求头
// res — 响应对象
res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' })
res.end('Hello World')
})
server.listen(3000, () => {
console.log('Server running at http://localhost:3000')
})const server = http.createServer((req, res) => {
// req — 请求对象
console.log(req.url) // 请求路径
console.log(req.method) // 请求方法
console.log(req.headers) // 请求头
// res — 响应对象
res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' })
res.end('Hello World')
})
server.listen(3000, () => {
console.log('Server running at http://localhost:3000')
})获取请求数据
js
const server = http.createServer((req, res) => {
let data = ''
req.on('data', (chunk) => {
data += chunk // 拼接数据块
})
req.on('end', () => {
console.log('完整数据:', data)
res.end('OK')
})
})const server = http.createServer((req, res) => {
let data = ''
req.on('data', (chunk) => {
data += chunk // 拼接数据块
})
req.on('end', () => {
console.log('完整数据:', data)
res.end('OK')
})
})JSONP 跨域
js
const url = require('url')
http.createServer((req, res) => {
const urlObj = url.parse(req.url, true)
res.end(`${urlObj.query.callback}(${JSON.stringify({ name: '张三', age: 18 })})`)
}).listen(3000)const url = require('url')
http.createServer((req, res) => {
const urlObj = url.parse(req.url, true)
res.end(`${urlObj.query.callback}(${JSON.stringify({ name: '张三', age: 18 })})`)
}).listen(3000)CORS 头跨域
js
http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'application/json;charset=utf-8',
'Access-Control-Allow-Origin': '*'
})
res.end(JSON.stringify({ name: '张三' }))
}).listen(3000)http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'application/json;charset=utf-8',
'Access-Control-Allow-Origin': '*'
})
res.end(JSON.stringify({ name: '张三' }))
}).listen(3000)URL 模块
parse(旧版)
js
const url = require('url')
const parsed = url.parse('/api?user=b&age=18', true)
// {
// pathname: '/api',
// query: { user: 'b', age: '18' },
// search: '?user=b&age=18',
// href: '/api?user=b&age=18'
// }
// format — 对象转 URL 字符串
url.format({
protocol: 'https',
host: 'www.baidu.com',
pathname: '/api',
query: { user: 'b' }
})
// 'https://www.baidu.com/api?user=b'
// resolve — 路径解析
url.resolve('/one/two', 'three') // '/one/three'
url.resolve('/one/two/', 'three') // '/one/two/three'const url = require('url')
const parsed = url.parse('/api?user=b&age=18', true)
// {
// pathname: '/api',
// query: { user: 'b', age: '18' },
// search: '?user=b&age=18',
// href: '/api?user=b&age=18'
// }
// format — 对象转 URL 字符串
url.format({
protocol: 'https',
host: 'www.baidu.com',
pathname: '/api',
query: { user: 'b' }
})
// 'https://www.baidu.com/api?user=b'
// resolve — 路径解析
url.resolve('/one/two', 'three') // '/one/three'
url.resolve('/one/two/', 'three') // '/one/two/three'URL 类(新版,推荐)
js
const myUrl = new URL('/api?user=b&age=18', 'http://localhost:3000')
myUrl.pathname // '/api'
myUrl.search // '?user=b&age=18'
myUrl.searchParams // URLSearchParams 对象
myUrl.searchParams.get('user') // 'b'const myUrl = new URL('/api?user=b&age=18', 'http://localhost:3000')
myUrl.pathname // '/api'
myUrl.search // '?user=b&age=18'
myUrl.searchParams // URLSearchParams 对象
myUrl.searchParams.get('user') // 'b'Path 模块
js
const path = require('path')
path.basename('/foo/bar/file.txt') // 'file.txt'
path.dirname('/foo/bar/file.txt') // '/foo/bar'
path.extname('/foo/bar/file.txt') // '.txt'
path.join('/foo', 'bar', 'baz') // '/foo/bar/baz'
path.resolve('./file.txt') // 当前工作目录 + 'file.txt' 的绝对路径
path.parse('/home/user/file.txt')
// { root: '/', dir: '/home/user', base: 'file.txt', ext: '.txt', name: 'file' }
path.format({ root: '/', dir: '/home/user', base: 'file.txt' })
// '/home/user/file.txt'const path = require('path')
path.basename('/foo/bar/file.txt') // 'file.txt'
path.dirname('/foo/bar/file.txt') // '/foo/bar'
path.extname('/foo/bar/file.txt') // '.txt'
path.join('/foo', 'bar', 'baz') // '/foo/bar/baz'
path.resolve('./file.txt') // 当前工作目录 + 'file.txt' 的绝对路径
path.parse('/home/user/file.txt')
// { root: '/', dir: '/home/user', base: 'file.txt', ext: '.txt', name: 'file' }
path.format({ root: '/', dir: '/home/user', base: 'file.txt' })
// '/home/user/file.txt'path.resolve vs path.join:
join:单纯拼接路径resolve:解析出绝对路径,/开头的路径会作为根目录
js
path.resolve('/aaa', '/bbb') // '/bbb'(最右侧绝对路径优先)
path.resolve('foo', 'bar') // '/current/working/dir/foo/bar'path.resolve('/aaa', '/bbb') // '/bbb'(最右侧绝对路径优先)
path.resolve('foo', 'bar') // '/current/working/dir/foo/bar'Querystring 模块
js
const querystring = require('querystring')
// 解析查询字符串为对象
querystring.parse('name=abc&age=18')
// { name: 'abc', age: '18' }
// 对象转查询字符串
querystring.stringify({ name: 'abc', age: '18' })
// 'name=abc&age=18'const querystring = require('querystring')
// 解析查询字符串为对象
querystring.parse('name=abc&age=18')
// { name: 'abc', age: '18' }
// 对象转查询字符串
querystring.stringify({ name: 'abc', age: '18' })
// 'name=abc&age=18'OS 模块
js
const os = require('os')
os.type() // 'Linux' / 'Darwin' / 'Windows_NT'
os.platform() // 'linux' / 'darwin' / 'win32'
os.release() // 操作系统版本号
os.homedir() // 用户目录
os.arch() // CPU 架构:'x64', 'arm64' 等
os.cpus() // CPU 详细信息(型号、速度、线程数)
os.networkInterfaces() // 网络接口信息const os = require('os')
os.type() // 'Linux' / 'Darwin' / 'Windows_NT'
os.platform() // 'linux' / 'darwin' / 'win32'
os.release() // 操作系统版本号
os.homedir() // 用户目录
os.arch() // CPU 架构:'x64', 'arm64' 等
os.cpus() // CPU 详细信息(型号、速度、线程数)
os.networkInterfaces() // 网络接口信息案例:跨平台打开浏览器
js
const { exec } = require('child_process')
function openBrowser(url) {
if (os.platform() === 'darwin') {
exec(`open ${url}`)
} else if (os.platform() === 'win32') {
exec(`start ${url}`)
} else {
exec(`xdg-open ${url}`)
}
}const { exec } = require('child_process')
function openBrowser(url) {
if (os.platform() === 'darwin') {
exec(`open ${url}`)
} else if (os.platform() === 'win32') {
exec(`start ${url}`)
} else {
exec(`xdg-open ${url}`)
}
}
Cao Note