node.js怎么配置访问本地的html文件

node.js怎么配置访问本地的html文件,第1张

可以尝试我开发的 前端开发 构建工具slow-cli

安装

npm install slow-cli -g

使用

在本地的html文件的目录下运行一次(以后就不用运行了)

slow init

然后运行

slow start

就可以了。 打开浏览器 localhost:3000/xx.html就可以 访问本地的html文件了。 详细的介绍可以看

https://github.com/huyinghuan/slow-cli/blob/master/README.zh.md

var http = require("http"),

url = require("url"),

path = require("path"),

fs = require("fs")

http.createServer(function (req, res) {

var pathname=__dirname+url.parse(req.url).pathname

if (path.extname(pathname)=="") {

pathname+="/"

}

if (pathname.charAt(pathname.length-1)=="/"){

pathname+="index.html"

}

path.exists(pathname,function(exists){

if(exists){

switch(path.extname(pathname)){

case ".html":

res.writeHead(200, {"Content-Type": "text/html"})

break

case ".js":

res.writeHead(200, {"Content-Type": "text/javascript"})

break

case ".css":

res.writeHead(200, {"Content-Type": "text/css"})

break

case ".gif":

res.writeHead(200, {"Content-Type": "image/gif"})

break

case ".jpg":

res.writeHead(200, {"Content-Type": "image/jpeg"})

break

case ".png":

res.writeHead(200, {"Content-Type": "image/png"})

break

default:

res.writeHead(200, {"Content-Type": "application/octet-stream"})

}

fs.readFile(pathname,function (err,data){

res.end(data)

})

} else {

res.writeHead(404, {"Content-Type": "text/html"})

res.end("<h1>404 Not Found</h1>")

}

})

}).listen(8080, "127.0.0.1")

console.log("Server running at http://127.0.0.1:8080/")

var http = require("http"),

url = require("url"),

path = require("path"),

fs = require("fs")

http.createServer(function (req, res) {

var pathname=__dirname+url.parse(req.url).pathname

if (path.extname(pathname)=="") {

pathname+="/"

}

if (pathname.charAt(pathname.length-1)=="/"){

pathname+="index.html"

}

path.exists(pathname,function(exists){

if(exists){

switch(path.extname(pathname)){

case ".html":

res.writeHead(200, {"Content-Type": "text/html"})

break

case ".js":

res.writeHead(200, {"Content-Type": "text/javascript"})

break

case ".css":

res.writeHead(200, {"Content-Type": "text/css"})

break

case ".gif":

res.writeHead(200, {"Content-Type": "image/gif"})

break

case ".jpg":

res.writeHead(200, {"Content-Type": "image/jpeg"})

break

case ".png":

res.writeHead(200, {"Content-Type": "image/png"})

break

default:

res.writeHead(200, {"Content-Type": "application/octet-stream"})

}

fs.readFile(pathname,function (err,data){

res.end(data)

})

} else {

res.writeHead(404, {"Content-Type": "text/html"})

res.end("<h1>404 Not Found</h1>")

}

})

}).listen(8080, "127.0.0.1")

console.log("Server running at http://127.0.0.1:8080/")


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/6150014.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-16
下一篇 2023-03-16

发表评论

登录后才能评论

评论列表(0条)

保存