node.js

2017-02-15  本文已影响0人  灬感同身受灬

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下载的文件夹
上一篇下一篇

猜你喜欢

热点阅读