结合fs发送文件数据
Content-Type需要设置charset字符编码,只有字符才需要设置。
// 引入http
var http = require("http");
var fs = require("fs");
// 创建
var server = http.createServer()
server.on("request", function(req, res) {
var url = req.url
if(url === "/"){
res.end("")
fs.readFile("./index.html", function(err,data) {
if(err) {
res.setHeader("Content-Type", "text/plain; charset=utf-8")
res.end("文件读取失败,请稍后重试!")
} else {
// data默认是二进制,通过toString转化成字符串
// res.end() 支持两种类型的数据,一是二进制,一是字符串
res.setHeader("Content-Type", "text/html; charset=utf-8")
res.end(data)
}
})
} else if(url === '/a') {
fs.readfile("./a.jpg", function(err, data) {
if(err) {
res.setHeader("Content-type", "text/plain; charset=utf-8")
res.end("文件读取失败,请稍后重试!")
} else {
// charset编码适用于字符,图片不需要设置。
res.setHeader("Content-Type", "image/jpg")
res.end(data)
}
})
}
})
server.lisen(3000, function() {
console.log("Server is rinning...")
})
index.html
<!DOCTYPE html>
<html>
<mate charset="utf-8">
<title>test1</title>
<body>
<h1>首页</h1>
<body>
</html>