我想运行一个非常简单的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?


当前回答

编辑:

Node.js示例应用Node Chat拥有你想要的功能。 在它的readme。textfile中 3.步伐就是你要找的。

step1 创建一个在端口8002上响应hello world的服务器 步骤2 创建一个index.html并服务它 步骤3 介绍util.js 更改逻辑,以便为任何静态文件提供服务 如果找不到文件,显示404 第四 添加jquery-1.4.2.js 添加client.js 将index.html更改为提示用户昵称

这是server.js

这是util.js

其他回答

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

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

最快捷的方法:

var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/../public')); // ← adjust
app.listen(3000, function() { console.log('listening'); });

你的方法:

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
    console.dir(req.url);

    // will get you  '/' or 'index.html' or 'css/styles.css' ...
    // • you need to isolate extension
    // • have a small mimetype lookup array/object
    // • only there and then reading the file
    // •  delivering it after setting the right content type

    res.writeHead(200, {'Content-Type': 'text/html'});

    res.end('ok');
}).listen(3001);

这里有很多复杂的答案。如果你不打算处理nodeJS文件/数据库,只是想提供静态html/css/js/图像,就像你的问题建议的那样,然后简单地安装pushstate-server模块或类似的;

这是一个“一行程序”,它将创建并启动一个迷你网站。只需将整个块粘贴到终端中相应的目录中。

mkdir mysite; \
cd mysite; \
npm install pushstate-server --save; \
mkdir app; \
touch app/index.html; \
echo '<h1>Hello World</h1>' > app/index.html; \
touch server.js; \
echo "var server = require('pushstate-server');server.start({ port: 3000, directory: './app' });" > server.js; \
node server.js

打开浏览器,访问http://localhost:3000。完成了。

服务器将使用应用程序目录作为根目录来提供文件。要添加额外的资产,只需将它们放在该目录中。