最简单的node服务

Node.js是基于Chrome V8引擎的Javascript运行环境
Node.js使用了一个事件驱动、非堵塞式I/O模型,使其轻量又高效
Node.js的包管理器npm,是全球最大的开源库生态系统

准备:node环境。
1、shell命令: mkdir NodeTest 新建NodeTest文件夹
2、cd NodeTest 进入文件夹
3、touch app.js 新建app.js文件
4、编写app.js文件,先开启服务

const http = require('http')

const myServer = http.createServer(function(req, res) {

})

myServer.listen(3000, function() {
    console.log('开启端口为3000的服务')
})

5、shell: node app.js 执行脚本

在这里插入图片描述

6、mkdir view 新建view文件夹
7、touch index.html 常规操作
8、app.js返回index的内容


const http = require('http')
const path = require('path')
const fs = require('fs')

const myServer = http.createServer(function(req, res) {
    const url = path.join('view', 'index.html')
    const content = fs.readFileSync(url)
    res.write(content)
    res.end() //服务器响应结束
})

myServer.listen(3000, function() {
    console.log('开启端口为3000的服务')
})

访问localhost:3000 即可看到页面
9、根据路由返回页面 在view下面新建info.html

const http = require('http')
const path = require('path')
const fs = require('fs')

const myServer = http.createServer(function(req, res) {
    console.log(req.url)
    const url = req.url === '/' ? 'index.html' : req.url  
    let fileUrl = path.join('view', url)
    fileUrl = fs.existsSync(fileUrl) ? fileUrl:path.join('view', 'err', '404err.html')
    const content = fs.readFileSync(fileUrl)
    res.write(content)
    res.end() //服务器响应结束
})

myServer.listen(3000, function() {
    console.log('开启端口为3000的服务')
})

在这里插入图片描述
细品

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值