使用node創建本地服務器訪問靜態文件

最終目錄結構

demo
│   node_modules
└───public
│   │   index.html
│   │   index.css
│   └───index.js
└───server.js

1、使用express框架的示例

1.下載express依賴javascript

cnpm install express

2.server.js代碼css

//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.public目錄裏面的index.html、index.css、index.js (其餘幾個方法公用這個文件夾的面問資源文件)html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>本地服務器</title>
		<meta charset="UTF-8" />
		<link rel="stylesheet" type="text/css" href="index.css"/>
		<script src="index.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<h3>本地服務器</h3>
	</body>
</html>
//index.css
body{
	background: #fff000;
}
//index.js
console.log("index.html加載了index.js")

4.運行 java

node server.js

2、使用koa框架的示例 

1.安裝koa koa-staticnode

cnpm install koa koa-static

注意:koa要求node的版本較高(node v7.6.0+),若是出現以下錯誤,要升級nodeexpress

koa-static@4.0.1@koa-static\index.js:39
return async function serve (ctx, next) {
             ^^^^^^^^
SyntaxError: Unexpected token function

2.server.js代碼以下npm

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端口")
});

3、使用fastify框架的示例  

1.安裝fastify serve-static服務器

cnpm install fastify serve-static

2.server.js代碼以下app

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端口");
})

3、不使用框架的示例

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端口");