Implementation ideas
- Import http, fs, path modules
- Create a web server
- Listen to the request, map the local file path, read the file and return
- start server
the code
// 1. 导入http、fs、path模块
const http = require(‘http’)
const fs = require(‘fs’)
const path = require(‘path’)
//2. Create a web server
const server = http.createServer()
//3. Listen to request
server.on('request', (req, res) => { // get url const url = req.url // map to local file path let myPath = '' if (url === '/') { myPath = path.join(__dirname, './test/index.html') } else { myPath = path.join(__dirname, './test', url) } // read file fs. readFile(myPath, 'utf-8', (err, data) => { if (err) return res. end('404') res. end(data) }) })
//4. Start the server
server.listen(8888, () => { console.log('8888 port server started!!! Request path: localhost:8888'); } )