nodejs 安裝
sudo apt-get install nodejs
sudo apt-get install npm```
#nodejs server代碼配置環境
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');
})```
所需要的模塊
- 創建服務器的代碼
-
使用了監聽事件回調函數
Paste_Image.png 吧http服務變成一個模塊
引用創建的模塊
項目
- models 項目模型
- views 視圖
- roune路由 controller控制
- uploads 文件上傳文件夾
- public 靜態文件
- app.js 主文件
- node_modules npm下載的文件夾