http - NodeJS 中的基本静态文件服务器

标签 http node.js webserver

我正在尝试在 nodejs 中创建一个静态文件服务器,而不是作为一个完美的服务器来理解 node。我非常了解 Connect 和 node-static 等项目,并且完全打算将这些库用于更多的生产就绪代码,但我也想了解我正在使用的基础知识。考虑到这一点,我编写了一个小型 server.js:

var http = require('http'),
    url = require('url'),
    path = require('path'),
    fs = require('fs');
var mimeTypes = {
    "html": "text/html",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "png": "image/png",
    "js": "text/javascript",
    "css": "text/css"};

http.createServer(function(req, res) {
    var uri = url.parse(req.url).pathname;
    var filename = path.join(process.cwd(), uri);
    path.exists(filename, function(exists) {
        if(!exists) {
            console.log("not exists: " + filename);
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.write('404 Not Found\n');
            res.end();
        }
        var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
        res.writeHead(200, mimeType);

        var fileStream = fs.createReadStream(filename);
        fileStream.pipe(res);

    }); //end path.exists
}).listen(1337);

我的问题是双重的

  1. 这是在 Node 中创建和流式传输基本 html 等的“正确”方法,还是有更好/更优雅/更健壮的方法?

  2. node 中的 .pipe() 基本上只是在做下面的事情吗?

.

var fileStream = fs.createReadStream(filename);
fileStream.on('data', function (data) {
    res.write(data);
});
fileStream.on('end', function() {
    res.end();
});

谢谢大家!

最佳答案

少即是多

只需在您的项目上先进入命令提示符并使用

$ npm install express

然后像这样编写你的 app.js 代码:

var express = require('express'),
app = express(),
port = process.env.PORT || 4000;

app.use(express.static(__dirname + '/public'));
app.listen(port);

然后,您将创建一个“公共(public)”文件夹来放置文件。我首先尝试了更难的方法,但是您必须担心 mime 类型,它只需要映射耗时的东西,然后担心响应类型等等等....不,谢谢。

关于http - NodeJS 中的基本静态文件服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7268033/

相关文章:

c# - HttpClient 等待 SendAsync 死锁

linux - HTTP 请求未响应 404 未找到

http - Arduino 集成开发环境/ESP8266 : Why does a button have to be pressed twice to get the correct output?

linux - 新鲜的 Centos 6 标准服务器安装有多安全?

ruby-on-rails - Rails 中的弱 ETAG?

node.js - NPM 无法在 Windows 上运行 - 路径中有两个 C 驱动器

javascript - forEach 循环中的异步函数和回调

mysql - 通过 Node MySQL 函数传递变量

php - 您如何将网站部署到您的网络服务器?

php - 如何按文件夹设置 error_log?