我想运行一个非常简单的HTTP服务器。对example.com的每个GET请求都应该得到index.html,但作为一个常规的HTML页面(即,与阅读普通网页时的体验相同)。

使用下面的代码,我可以读取index.html的内容。我如何服务index.html作为一个普通的网页?

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end(index);
}).listen(9615);

下面的一个建议很复杂,需要我为我想使用的每个资源(CSS、JavaScript、图像)文件写一个get行。

我如何能提供一个单一的HTML页面与一些图像,CSS和JavaScript?


当前回答

你不需要使用任何npm模块来运行一个简单的服务器,有一个非常小的库叫做“npm Free server”用于Node:

50行代码 如果您正在请求文件或文件夹,则输出 如果失败或工作,则显示红色或绿色 大小小于1KB(缩小版) 完全评论,所以你可以根据需要调整它

npm-free-server(在GitHub)

其他回答

我遇到的更简单的版本如下。出于教育目的,它是最好的,因为它不使用任何抽象库。

var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs');

var mimeTypes = {
  "html": "text/html",
  "mp3":"audio/mpeg",
  "mp4":"video/mp4",
  "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);
    fs.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();
            return;
        }
        var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
        res.writeHead(200, {'Content-Type':mimeType});

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

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

现在进入浏览器,打开以下内容:

http://127.0.0.1/image.jpg

这里image.jpg应该和这个文件在同一个目录下。 希望这能帮助到一些人:)

我在npm上发现了一个有趣的库,可能对你有用。它叫做mime(npm install mime或https://github.com/broofa/node-mime),它可以确定文件的mime类型。下面是我用它写的一个web服务器的例子:

var mime = require("mime"),http = require("http"),fs = require("fs");
http.createServer(function (req, resp) {
path  = unescape(__dirname + req.url)
var code = 200
 if(fs.existsSync(path)) {
    if(fs.lstatSync(path).isDirectory()) {
        if(fs.existsSync(path+"index.html")) {
        path += "index.html"
        } else {
            code = 403
            resp.writeHead(code, {"Content-Type": "text/plain"});
            resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
        }
    }
    resp.writeHead(code, {"Content-Type": mime.lookup(path)})
    fs.readFile(path, function (e, r) {
    resp.end(r);

})
} else {
    code = 404
    resp.writeHead(code, {"Content-Type":"text/plain"});
    resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
}
console.log("GET "+code+" "+http.STATUS_CODES[code]+" "+req.url)
}).listen(9000,"localhost");
console.log("Listening at http://localhost:9000")

这将服务于任何常规的文本或图像文件(.html, .css, .js, .pdf, .jpg, .png, .m4a和.mp3是我测试过的扩展名,但理论上它应该适用于所有文件)

开发人员指出

下面是我用它得到的输出示例:

Listening at http://localhost:9000
GET 200 OK /cloud
GET 404 Not Found /cloud/favicon.ico
GET 200 OK /cloud/icon.png
GET 200 OK /
GET 200 OK /501.png
GET 200 OK /cloud/manifest.json
GET 200 OK /config.log
GET 200 OK /export1.png
GET 200 OK /Chrome3DGlasses.pdf
GET 200 OK /cloud
GET 200 OK /-1
GET 200 OK /Delta-Vs_for_inner_Solar_System.svg

注意路径构造中的unescape函数。这是为了允许包含空格和编码字符的文件名。

注:此答案来自2011年。然而,它仍然有效。

你可以在Node.js中使用Connect和ServeStatic:

使用NPM安装connect和service -static $ NPM install connect service -static 创建server.js文件,内容如下: Var connect = require('connect'); var serveStatic = require(' service -static'); connect () .use (serveStatic (__dirname)) .listen(8080, () => console.log('服务器运行在8080…')); 使用Node.js运行 $ node server.js

您现在可以访问http://localhost:8080/yourfile.html

与其处理switch语句,我认为从字典中查找内容类型更简洁:

var contentTypesByExtension = {
    'html': "text/html",
    'js':   "text/javascript"
};

...

    var contentType = contentTypesByExtension[fileExtension] || 'text/plain';

Express函数sendFile正是你所需要的,因为你想从节点的web服务器功能,Express是自然的选择,然后服务静态文件变得简单:

res.sendFile('/path_to_your/index.html')

更多信息请点击:https://expressjs.com/en/api.html#res.sendFile

一个用express web server for node的小例子:

var express = require('express');
var app = express();
var path = require('path');

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.listen(8080);

运行这个,并导航到http://localhost:8080

在此基础上,允许你提供css和图像等静态文件,下面是另一个例子:

var express = require('express');
var app = express();
var path = require('path');

app.use(express.static(__dirname + '/css'));

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.listen(8080);

所以创建一个名为css的子文件夹,把你的静态内容放在里面,它将被你的index.html用于方便引用,比如:

<link type="text/css" rel="stylesheet" href="/css/style.css" />

注意href中的相对路径!

拖鞋!