【Node.js】URL 模块

自动重启服务器的插件nodemon: npm i -g nodemon。或者 node-dev 也可以:npm i -g node-dev。

parse,format,resolve 为旧版写法。

parse

js 复制代码
import url from 'url'
const urlString = 'https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110'
const parsedStr = url.parse(urlString)
console.log(parsedStr)

使用 const parsedStr = url.parse(urlString, true) 时,会将 query 转换为对象的形式:

format

js 复制代码
import url from 'url'
const urlObject = {
  protocol: 'https:',
  slashes: true,
  auth: null,
  host: 'www.baidu.com:443',
  port: '443',
  hostname: 'www.baidu.com',
  hash: '#tag=110',
  search: '?id=8&name=mouse',
  query: { id: '8', name: 'mouse' },
  pathname: '/ad/index.html',
  path: '/ad/index.html?id=8&name=mouse'
}
const parsedObj = url.format(urlObject)
console.log(parsedObj)

resolve

js 复制代码
import url from 'url'
// url.resolve(from, to)
var a = url.resolve('/one/two/three', 'four')
var e = url.resolve('/one/two/three/', 'four')
var b = url.resolve('http://example.com/', '/one')
var c = url.resolve('http://example.com/one', '/two')
var d = url.resolve('http://example.com/one/', 'three')
console.log(a + "," + e + "," + b + "," + c + "," + d)

总结一下就是:1. 没有域名的地址,在地址最后一个 / 后进行拼接。2. 有域名的地址,to 含有 / ,直接拼接到域名之后,没有/,拼接到 from 的后面。

新版写法 new URL。

js 复制代码
import http from 'http'
import url from 'url'
// 创建本地服务器接收数据
const server = http.createServer((req, res) => {
  const myUrl = new URL(req.url, 'http://127.0.0.1:3000')
  console.log(myUrl)
  res.writeHead(200, { 
    'Content-Type': 'application/json' 
  })
  res.end(JSON.stringify({
    data: "hello"
  }))
})
server.listen(8000,()=> {
  console.log("server is running")
})
js 复制代码
const myURL = new URL('/foo', 'https://example.org/');
// https://example.org/foo

查询参数:

js 复制代码
const myURL = new URL('https://example.org/abc?foo=~bar');
console.log(myURL.search);  // ?foo=~bar

其他用法都在官方文档,写的很清楚。Node.js 中文网

相关推荐
liangshanbo121510 小时前
Webpack 文件指纹面试题整理
前端·webpack·node.js
liangshanbo121511 小时前
Webpack 常见 Plugin 面试题
前端·webpack·node.js
liangshanbo121512 小时前
Webpack Tree Shaking 面试题整理
前端·webpack·node.js
搬砖的小码农_Sky13 小时前
AI Agent:Node.js和浏览器运行环境的本质区别
javascript·node.js·人机交互
李游Leo14 小时前
HarmonyOS 7 ArkTS + Node.js:把权限声明、运行时授权与隐私文案做成提审前一致性扫描【鸿蒙心迹】
华为·node.js·harmonyos
liangshanbo121515 小时前
Webpack的分包策略面试题
前端·webpack·node.js
搬砖的小码农_Sky1 天前
AI Agent:Windows上Node.js安装后 npm -v报错
前端·npm·node.js·人机交互
liangshanbo12152 天前
面试题:如何优化 Webpack 的打包速度?
前端·webpack·node.js
2601_962177302 天前
Windows 安装 Codex CLI 入门级教程
人工智能·windows·node.js·ai编程
光影少年3 天前
RN与Flutter架构区别
前端·flutter·react native·react.js·架构·node.js