node.js

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
  1. 創建服務器的代碼
Paste_Image.png
  1. 使用了監聽事件回調函數


    Paste_Image.png
  2. 吧http服務變成一個模塊

Paste_Image.png

引用創建的模塊

Paste_Image.png

項目

  1. models 項目模型
  2. views 視圖
  3. roune路由 controller控制
  4. uploads 文件上傳文件夾
  5. public 靜態文件
  6. app.js 主文件
  7. node_modules npm下載的文件夾
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Chapter01.簡介 NodeJS是讓JavaScript脫離瀏覽器運行在服務器的一個平臺,不是語言。 Nod...
    JunChow520閱讀 967評論 0 9
  • 搭建開發環境并模擬交互數據 一、實驗說明 下述介紹為實驗樓默認環境,如果您使用的是定制環境,請修改成您自己的環境介...
    玄月府的小妖在debug閱讀 2,152評論 0 15
  • 個人入門學習用筆記、不過多作為參考依據。如有錯誤歡迎斧正 目錄 簡書好像不支持錨點、復制搜索(反正也是寫給我自己看...
    kirito_song閱讀 2,500評論 1 37
  • 什么是nodejs里的模塊? 我們寫程序的時候一般會把比較復雜而又低耦合的代碼會封裝到一起,nodejs也不例外。...
    云華兄閱讀 1,288評論 0 1
  • 格力電器的董阿姨在股東大會上發飆了,80%的人在圍觀視頻,可能只有20%的人能真正看懂格力,而能從這個事情中通過思...
    牛奶tiger閱讀 143評論 1 0