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,156评论 0 15
  • 个人入门学习用笔记、不过多作为参考依据。如有错误欢迎斧正 目录 简书好像不支持锚点、复制搜索(反正也是写给我自己看...
    kirito_song阅读 2,505评论 1 37
  • 什么是nodejs里的模块? 我们写程序的时候一般会把比较复杂而又低耦合的代码会封装到一起,nodejs也不例外。...
    云华兄阅读 1,291评论 0 1
  • 格力电器的董阿姨在股东大会上发飙了,80%的人在围观视频,可能只有20%的人能真正看懂格力,而能从这个事情中通过思...
    牛奶tiger阅读 148评论 1 0