A little front-end knowledge every day 03 - Node handwritten server

Implementation ideas

  1. Import http, fs, path modules
  2. Create a web server
  3. Listen to the request, map the local file path, read the file and return
  4. 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'); } )

renderings

insert image description here

Guess you like

Origin blog.csdn.net/qq_33591873/article/details/127975184