NodeJS

处理URL

URL

代码示例:

// server.js

const http = require('http')
const moduleRenderHTML = require('./module/renderHTML')
const moduleRenderStatus = require('./module/renderStatus')
const {fileURLToPath, urlToHttpOptions} = require('url')

// const myURL = new URL('https://a:b@测试?foo#bar')

// console.log(myURL.toString())  // 中文需要指定utf-8编码

// console.log(fileURLToPath('file://c://foo.txt'))

// const myURL = new URL('https://a:b@测试?foo#bar')
// console.log(urlToHttpOptions(myURL))

http.createServer((req, res) => {
    const myURL = new URL(req.url, 'http://localhost:3000')  // 拼接
    // console.log(myURL)
    // for (let [key, value] of myURL.searchParams) {  // [key, value]:解构
    //     console.log(key, value)
    // }
    // myURL.searchParams.get('foo')
    res.writeHead(moduleRenderStatus.renderStatus(myURL.pathname), {'Content-Type': 'text/html;charset=utf-8'})
    if (req.url === '/favicon.ico') {
        return
    }
    res.write(moduleRenderHTML.renderHTML(myURL.pathname))
    res.end()
}).listen(3000, () => {
    console.log('server start')
})