静态服务

要使用 Node.js 创建一个简单的静态文件服务器,你可以使用 Node.js 的内置 http 模块,配合 fs(文件系统)模块来读取并返回静态文件内容。这里有一个简单的示例说明如何做到这一点。

步骤 1: 创建一个基本的 HTTP 服务器
首先,你需要使用 http 模块来创建一个基本的 web 服务器,它将侦听特定的端口上的 HTTP 请求。

步骤 2: 使用 fs 模块读取请求的文件
当接收到一个请求时,使用 fs 模块来读取对应的静态文件。你需要根据请求的 URL 来寻找对应的文件路径。

步骤 3: 返回静态文件内容
读取文件后,将文件内容作为响应返回。如果文件不存在,你可以返回 404 状态码。

下面是一个简单的示例代码:

const http = require('http');
const fs = require('fs');
const path = require('path');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    console.log('Request for ' + req.url + ' by method ' + req.method);

    // 默认访问index.html文件
    let filePath = '.' + req.url;
    if (filePath == './') {
        filePath = './index.html';
    }

    const extname = String(path.extname(filePath)).toLowerCase();
    const mimeTypes = {
        '.html': 'text/html',
        '.js': 'text/javascript',
        '.css': 'text/css',
        '.json': 'application/json',
        '.png': 'image/png',
        '.jpg': 'image/jpg',
        '.gif': 'image/gif',
    };

    // 默认内容类型为text/plain
    let contentType = mimeTypes[extname] || 'text/plain';

    fs.readFile(filePath, function(error, content) {
        if (error) {
            if(error.code == 'ENOENT'){
                fs.readFile('./404.html', function(error, content) {
                    res.writeHead(404, { 'Content-Type': 'text/html' });
                    res.end(content, 'utf-8');
                });
            } else {
                res.writeHead(500);
                res.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
            }
        } else {
            res.writeHead(200, { 'Content-Type': contentType });
            res.end(content, 'utf-8');
        }
    });
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

这个代码将启动一个 HTTP 服务器,它侦听 127.0.0.1(localhost)上的 3000 端口。服务器将尝试根据请求的 URL 返回对应的文件。例如,如果你访问 http://127.0.0.1:3000/,服务器将尝试返回当前目录下的 index.html 文件。

注意,这个简单的静态文件服务器是一个演示,可能不适合生产环境使用。对于实际项目,考虑使用专门的静态文件服务器软件,如 Nginx,或者使用 Node.js 的扩展模块,如 express 和其 static 中间件,来更容易地管理静态资源。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容