Nodejs搭建一個的本地靜態檔案伺服器的方法
阿新 • • 發佈:2018-12-14
方法一:
第一步:在Nodejs安裝目錄安裝:
npm install connect
第二步:在Nodejs安裝目錄安裝:
npm install serve-static
第三步:新建server.js (可以放在專案裡去執行也可以放在Nodejs安裝目錄下執行):
var connect = require("connect");
var serveStatic = require("serve-static");
var app = connect();
app.use(serveStatic("D:\專案資料夾"));
app.listen(5000);
第四步:
執行node server.js
方法二:使用express框架的示例
1.下載express依賴
npm install express
2.新建server.js (可以放在專案裡去執行也可以放在Nodejs安裝目錄下執行):
//server.js var express = require('express'); var app = express(); app.use(express.static('public'));//express.static是express提供的內建的中介軟體用來設定靜態檔案路徑 app.get('/index.htm', function (req, res) { res.sendFile(__dirname + "/" + "index.htm"); }) var server = app.listen(3000, function () { console.log("監聽3000埠") })
3.執行node server.js
方法三:使用koa框架的示例
1.安裝koa koa-static
npm install koa koa-static
注意:koa要求node的版本較高(node v7.6.0+),如果出現如下錯誤,要升級node
[email protected]@koa-static\index.js:39
return async function serve (ctx, next) {
^^^^^^^^
SyntaxError: Unexpected token function
2.server.js程式碼如下
const Koa = require('koa');
const app = new Koa();
const path = require('path');
const serve = require('koa-static');
const main = serve(path.join(__dirname+'/public'));
app.use(main);
app.listen(3001,function(){
console.log("監聽3001埠")
});
方法四、使用fastify框架的示例
1.安裝fastify serve-static
npm install fastify serve-static
2.server.js程式碼如下
const serveStatic = require('serve-static');
const fastify = require('fastify')();
const path = require('path');
fastify.use('/', serveStatic(path.resolve(__dirname, 'public')));
fastify.listen(3002, function () {
console.log("監聽3002埠");
})
方法五、不使用框架的示例
server.js(不需要引入任何第三方依賴)
var url = require("url"),
fs = require("fs"),
http = require("http"),
path = require("path");
http.createServer(function (req, res) {
var pathname = __dirname + url.parse("/public"+req.url).pathname;//資源指向public目錄
if (path.extname(pathname) == "") {
pathname += "/";
}
if (pathname.charAt(pathname.length - 1) == "/") {
pathname += "index.html";
}
fs.exists(pathname, function (exists) {
if (exists) {
switch(path.extname(pathname)){
case ".html":
res.writeHead(200, {"Content-Type": "text/html"});
break;
case ".js":
res.writeHead(200, {"Content-Type": "text/javascript"});
break;
case ".css":
res.writeHead(200, {"Content-Type": "text/css"});
break;
case ".gif":
res.writeHead(200, {"Content-Type": "image/gif"});
break;
case ".jpg":
res.writeHead(200, {"Content-Type": "image/jpeg"});
break;
case ".png":
res.writeHead(200, {"Content-Type": "image/png"});
break;
default:
res.writeHead(200, {"Content-Type": "application/octet-stream"});
}
fs.readFile(pathname, function (err, data) {
res.end(data);
});
} else {
res.writeHead(404, {
"Content-Type": "text/html"
});
res.end("<h1>404 Not Found</h1>");
}
});
}).listen(3003);
console.log("監聽3003埠");
以上內容均參考他人