美文网首页
创建服务和读取文件

创建服务和读取文件

作者: 晨露_cb9a | 来源:发表于2019-01-23 16:03 被阅读0次

const http = require('http')

const fs = require('fs')

// 读取内容:

// fs.readFile(路径,[编码],function(err,data){ //异步过程

// })

// 创建一个服务

var httpObj = http.createServer(function (req, res) {

// 第一种方式

var url = req.url=== '/' ? '/index' : res.url

fs.readFile('www' + url + '.html',function (err, data) {

if (err) {

console.log('404')

}else {

res.write(data)

res.end()

}

})

// 第二种方式

switch (req.url) {

case '/':

            // 读取文件

            fs.readFile('www/index.html',function (err, data) {

if (err) {

console.log('404!')

}else {

res.write(data)

res.end()

}

})

break

        case '/a':

            fs.readFile('www/a.html',function (err, data) {

if (err) {

console.log('404!')

}else {

res.write(data)

res.end()

}

})

break

        case '/b':

            fs.readFile('www/b.html',function (err, data) {

if (err) {

console.log('404')

}else {

res.write(data)

res.end()

}

})

default:

            fs.readFile('www/index.html',function (err, data) {

if (err) {

console.log('404')

}else {

res.write(data)

res.end()

}

})

}

})

httpObj.listen(1000)

相关文章

网友评论

      本文标题:创建服务和读取文件

      本文链接:https://www.haomeiwen.com/subject/uyxsjqtx.html