文件流
var fs = require('fs');
var writeStream = fs.createWriteStream('要写入内容的文件地址')
writeStream.write('要写入的内容', 'utf-8');
writeStream.end()
writeStream.on('finish', function() {})
writeStream.on('error', function() {})
var readStream = fs.createReadStream('要读取内容的文件地址');
var text = ''
readStream.on('data', function(chunk) {
text += chunk
})
readStream.on('end', function() {})
readStream.on('error', function() {})
readStream.pipe(writeStream)
http/url/fs混用搭建服务器
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
http.createServer(function(req, res) {
var pathname = url.parse(req.url).pathname;
var extname = path.extname(pathname);
pathname = pathname == '/' ? '默认渲染的html文件的地址' : pathname
function getExtType (ext) {
var str = ''
switch (ext) {
case '.html':
str = "text/html"
break;
case '.css':
str = "text/css"
break;
case '.js':
str = "text/javascript"
break;
}
return str
}
var type = getExtType(extname)
fs.readFile('./static' + pathname, function(err, data) {
if(err) {
fs.readFile('要渲染的错误文件的文件地址', function(err, errPage) {
res.writeHead(404, {"Content-type": `${type};charset=utf-8`})
res.write(errPage)
res.end()
})
} else {
res.writeHead(200, {"Content-type": `${type};charset=utf-8`})
res.write(data)
res.end()
}
})
}).listen(3000, function() {
})