nodejs 安裝
sudo apt-get install nodejs
sudo apt-get install npm```
#nodejs server代碼配置環(huán)境
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};
function send404(response) {
response.writeHead(404, {"Content-Type": text / plain});
response.write('Error 404 ');
response.end();
}
function sendFile(response, filePath, fileContents) {
response.writeHead(200, {"Content-type": mime.lookup(path.basename(filePath))});
response.end(fileContents);
}
function serveStatic(response, cache, absPath) {
if (cache[absPath]) {
console.log(cache[absPath])
sendFile(response, absPath, cache[absPath])
} else {
fs.exists(absPath, function (exists) {
if (exists) {
fs.readFile(absPath, function (err, data) {
if (err) {
send404(response)
} else {
console.log(data);
cache[absPath]=data
sendFile(response,absPath,data)
}
})
}else {
console.log('5');
send404(response)
}
})
}
}
var server = http.createServer(function(request,response){
var filePath = false;
if (request.url=='/'){
filePath='index.html';
}else{
filePath=request.url;
}
console.log(filePath);
var absPath='./'+filePath;
console.log(absPath);
serveStatic(response,cache,absPath);
})
server.listen(3000,function(){
console.log('ok');
})```
所需要的模塊
- 創(chuàng)建服務(wù)器的代碼
-
使用了監(jiān)聽事件回調(diào)函數(shù)
Paste_Image.png 吧http服務(wù)變成一個(gè)模塊
引用創(chuàng)建的模塊
項(xiàng)目
- models 項(xiàng)目模型
- views 視圖
- roune路由 controller控制
- uploads 文件上傳文件夾
- public 靜態(tài)文件
- app.js 主文件
- node_modules npm下載的文件夾