node搭建本地服务器

时间:2022-08-31 17:05:03

  随着前端不断发展,node基本已经成为必备,在调试的时候经常需要服务器,在之前的做法通常是去下载一个phpstudy 或者 xampp等启动一个服务,作为一个前端人虽然可以借助各种工具,但是怎么能不懂node如何搭建?为大家分享下代码,直接用就可以

  node原生

var http=require('http');
var fs=require('fs');
var root="C:/Users/Administrator/Desktop/layuicms2.0"
//开启服务
var server=http.createServer(function(req,res){
var url=req.url;
var file = root+url;
fs.readFile(file,function(err,data){
if(err){
res.writeHeader(404,{
'content-type' : 'text/html;charset="utf-8"'
});
res.write('<h1>404错误</h1><p>你要找的页面不存在</p>');
res.end();
}else{
res.writeHeader(200,{
'content-type' : 'text/html;charset="utf-8"'
});
res.write(data);//将index.html显示在客户端
res.end(); }
})
}).listen(8888);
console.log('服务器开启成功');

express

var root="C:/Users/Administrator/Desktop/layuicms2.0"
var express = require("express");
var path = require("path");
var app = express();
app.get("*",function(req,res){
res.sendFile(path.join(root,req.path),{},function(error){
if(error){
res.end("<h1>404<h1>");
}
return ;
});
})
app.listen("8080",function(err){
if(err){
console.log(err);
return;
}
console.log("listen at http://192.168.0.1:8080 \n or \n http://localhost:8080");
})