Nodejs 简单的静态服务器接口

Nodejs 简单的静态服务器接口

简单的静态服务器接口, 直接上代码.

exports.start = function() {
	var http = require("http"),
		url  = require("url"),
		path = require("path"),
		fs   = require("fs");
	
	var server = http.createServer(function (req, res) {
		//res.setHeader('Connection', 'keep-alive');
		//res.setHeader('Expires', 'Mon, 31 Dec 2012 23:59:59 GMT');
		//res.setHeader('Cache-Control', 'max-age=31536000');
		
		var pathname = __dirname + url.parse(req.url).pathname;
		if(path.extname(pathname) == "") {
			pathname += "/";
		}
		if(pathname.charAt(pathname.length - 1) == "/") {
			pathname += "index.html";
		}
		
		path.exists(pathname, function(exists) {
			if(exists) {
				var type = {
					".html": "text/html",
					".htm": "text/html",
					".js": "text/javascript",
					".css": "text/css",
					".ico": "image/x-icon",
					".jpeg": "image/jpeg",
					".jpg": "image/jpeg",
					".png": "image/png",
					".gif": "image/gif",
					".xml": "text/xml",
					".json": "application/json",
					".txt": "text/plain",
					".pdf": "application/pdf",
					".swf": "application/x-shockwave-flash"
				};
				res.writeHead(200, {"Content-Type": type[path.extname(pathname)]});
				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(8080, "127.0.0.1");
	
	console.log("Server is running at http://127.0.0.1:8080/");
	
	return server;
}

3 回复

Node.js 简单的静态服务器接口

在本篇中,我们将创建一个简单的静态文件服务器。通过使用Node.js内置的模块,我们可以轻松地实现这一功能。

示例代码

// 引入所需的模块
var http = require("http"),
    url  = require("url"),
    path = require("path"),
    fs   = require("fs");

// 创建HTTP服务器
var server = http.createServer(function (req, res) {
    // 获取请求的路径
    var pathname = __dirname + url.parse(req.url).pathname;

    // 如果路径以斜杠结尾,则添加默认的index.html文件
    if (path.extname(pathname) === "") {
        pathname += "/";
    }
    if (pathname.charAt(pathname.length - 1) === "/") {
        pathname += "index.html";
    }

    // 检查文件或目录是否存在
    path.exists(pathname, function (exists) {
        if (exists) {
            // 定义不同文件类型的MIME类型
            var type = {
                ".html": "text/html",
                ".htm": "text/html",
                ".js": "text/javascript",
                ".css": "text/css",
                ".ico": "image/x-icon",
                ".jpeg": "image/jpeg",
                ".jpg": "image/jpeg",
                ".png": "image/png",
                ".gif": "image/gif",
                ".xml": "text/xml",
                ".json": "application/json",
                ".txt": "text/plain",
                ".pdf": "application/pdf",
                ".swf": "application/x-shockwave-flash"
            };

            // 设置响应头
            res.writeHead(200, {"Content-Type": type[path.extname(pathname)]});

            // 读取文件并发送给客户端
            fs.readFile(pathname, function (err, data) {
                if (err) {
                    console.error(err);
                    res.writeHead(500, {"Content-Type": "text/plain"});
                    res.end("Internal Server Error");
                } else {
                    res.end(data);
                }
            });
        } else {
            // 如果文件不存在,返回404错误
            res.writeHead(404, {"Content-Type": "text/html"});
            res.end("<h1>404 Not Found</h1>");
        }
    });
});

// 监听端口
server.listen(8080, "127.0.0.1");

console.log("Server is running at http://127.0.0.1:8080/");

解释

  1. 引入模块:我们首先引入了Node.js内置的httpurlpathfs模块。
  2. 创建服务器:使用http.createServer方法创建一个HTTP服务器,并提供一个处理请求的回调函数。
  3. 解析请求路径:通过url.parse(req.url).pathname获取请求的路径,并将其与当前工作目录结合,得到完整的文件路径。
  4. 处理默认文件:如果请求路径以斜杠结尾,自动添加index.html作为默认文件。
  5. 检查文件存在性:使用path.exists方法检查请求的文件或目录是否存在。
  6. 设置响应头:根据文件扩展名设置相应的MIME类型,并使用res.writeHead方法设置响应头。
  7. 读取并发送文件:使用fs.readFile方法读取文件内容,并将其发送到客户端。如果发生错误,则返回500内部服务器错误。
  8. 处理404错误:如果文件不存在,则返回404 Not Found错误页面。

通过上述步骤,我们就可以创建一个简单的静态文件服务器,支持多种文件类型,并能正确处理默认文件和错误情况。


好文。 遇到简单地传送静态html的时候,不用redirect了。

好的,下面是针对“Nodejs 简单的静态服务器接口”的详细解释及示例代码。

示例代码

const http = require("http");
const url = require("url");
const path = require("path");
const fs = require("fs");

exports.start = function() {
    const server = http.createServer((req, res) => {
        let pathname = __dirname + url.parse(req.url).pathname;

        if (path.extname(pathname) === "") {
            pathname += "/";
        }
        
        if (pathname.charAt(pathname.length - 1) === "/") {
            pathname += "index.html";
        }

        fs.access(pathname, fs.constants.F_OK, (err) => {
            if (!err) {
                const contentType = {
                    ".html": "text/html",
                    ".htm": "text/html",
                    ".js": "text/javascript",
                    ".css": "text/css",
                    ".ico": "image/x-icon",
                    ".jpeg": "image/jpeg",
                    ".jpg": "image/jpeg",
                    ".png": "image/png",
                    ".gif": "image/gif",
                    ".xml": "text/xml",
                    ".json": "application/json",
                    ".txt": "text/plain",
                    ".pdf": "application/pdf",
                    ".swf": "application/x-shockwave-flash"
                };

                const extname = path.extname(pathname);
                const contentType = contentType[extname] || "application/octet-stream";

                res.writeHead(200, { "Content-Type": contentType });
                fs.createReadStream(pathname).pipe(res);
            } else {
                res.writeHead(404, { "Content-Type": "text/html" });
                res.end("<h1>404 Not Found</h1>");
            }
        });
    }).listen(8080, "127.0.0.1");

    console.log("Server is running at http://127.0.0.1:8080/");

    return server;
};

解释

  1. 引入模块:

    • http: 提供HTTP服务器和客户端功能。
    • url: 用于解析URL。
    • path: 提供处理文件路径的功能。
    • fs: 提供文件系统相关的功能。
  2. 创建HTTP服务器:

    • 使用http.createServer()方法创建一个HTTP服务器,并定义请求处理函数。
    • reqres 分别表示请求对象和响应对象。
  3. 解析URL路径:

    • 使用url.parse(req.url).pathname获取请求路径。
    • 如果路径是目录,则默认添加index.html作为首页。
  4. 检查文件是否存在:

    • 使用fs.access()方法检查文件或目录是否存在。
    • 如果文件存在,则设置相应的Content-Type头,并读取文件内容返回给客户端。
    • 如果文件不存在,则返回404状态码和错误信息。
  5. 返回服务器实例:

    • 最后返回创建的HTTP服务器实例。

这样,你就实现了一个简单的静态服务器接口,可以用来提供HTML、CSS、JS等静态文件。

回到顶部