欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

node.js学习之搭建简易服务器

程序员文章站 2022-04-18 11:29:14
...

node.js搭建一个服务器

文件夹结构

server->static->index.html (index Page)

                     ->detail.html (detail Page)

                     ->list.html (list Page)

          ->index.js

         ->router.js(配置路由)


router.js

module.exports = {
    '/': 'static/index.html',
    '/detail': 'static/detail.html',
    '/list': 'static/list.html'
}

index.js

//引入核心模块
const http = require('http')
const fs = require('fs')
const path = require('path')
//引入自定义模块(注意路径)
const router = require('./router')
http.createServer((request, response) => {
    if(request.url !== 'favicon.ico'){
        //__dirname是当前文件的文件夹目录
        const filePath = path.join(__dirname, request[request.url])
        fs.readFile(filePath, (err, data) => {
            if(err) console.error(err)
            else response.end(data)
        }
    }
}).listen(8080)

这样一个简易的服务器就搭建好了