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


当前回答

你可以在shell中输入这些

npx serve

回购:https://github.com/zeit/serve。

其他回答

你不需要快递。你不需要联系。Node.js执行http native。你所需要做的就是根据请求返回一个文件:

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

http.createServer(function (request, response) {
    var requestUrl = url.parse(request.url)    
    response.writeHead(200)
    fs.createReadStream(requestUrl.pathname).pipe(response)  // do NOT use fs's sync methods ANYWHERE on production (e.g readFileSync) 
}).listen(9615)    

一个更完整的例子,确保请求不能访问基目录下的文件,并进行适当的错误处理:

var http = require('http')
var url = require('url')
var fs = require('fs')
var path = require('path')
var baseDirectory = __dirname   // or whatever base directory you want

var port = 9615

http.createServer(function (request, response) {
    try {
        var requestUrl = url.parse(request.url)

        // need to use path.normalize so people can't access directories underneath baseDirectory
        var fsPath = baseDirectory+path.normalize(requestUrl.pathname)

        var fileStream = fs.createReadStream(fsPath)
        fileStream.pipe(response)
        fileStream.on('open', function() {
             response.writeHead(200)
        })
        fileStream.on('error',function(e) {
             response.writeHead(404)     // assume the file doesn't exist
             response.end()
        })
   } catch(e) {
        response.writeHead(500)
        response.end()     // end the response so browsers don't hang
        console.log(e.stack)
   }
}).listen(port)

console.log("listening on port "+port)

编辑:

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

看看这个要点。我在这里复制它以供参考,但要点已定期更新。

Node.JS静态文件web服务器。将它放在您的路径中以启动任何目录中的服务器,需要一个可选的端口参数。

var http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs"),
    port = process.argv[2] || 8888;

http.createServer(function(request, response) {

  var uri = url.parse(request.url).pathname
    , filename = path.join(process.cwd(), uri);

  fs.exists(filename, function(exists) {
    if(!exists) {
      response.writeHead(404, {"Content-Type": "text/plain"});
      response.write("404 Not Found\n");
      response.end();
      return;
    }

    if (fs.statSync(filename).isDirectory()) filename += '/index.html';

    fs.readFile(filename, "binary", function(err, file) {
      if(err) {        
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(err + "\n");
        response.end();
        return;
      }

      response.writeHead(200);
      response.write(file, "binary");
      response.end();
    });
  });
}).listen(parseInt(port, 10));

console.log("Static file server running at\n  => http://localhost:" + port + "/\nCTRL + C to shutdown");

更新

gist确实处理css和js文件。我自己也用过。在“二进制”模式下使用读/写不是问题。这仅仅意味着文件库不会将文件解释为文本,并且与响应中返回的内容类型无关。

你的代码的问题是你总是返回一个“文本/纯”的内容类型。上面的代码不返回任何内容类型,但如果您只是将其用于HTML、CSS和JS,浏览器可以很好地推断出这些内容。没有内容类型总比错误的内容类型好。

通常情况下,content-type是web服务器的配置。因此,如果这不能解决您的问题,我很抱歉,但是作为一个简单的开发服务器,它对我来说是有效的,我认为它可能对其他人有所帮助。如果确实需要响应中正确的内容类型,则需要像joeytwiddle那样显式地定义它们,或者使用像Connect这样具有合理默认值的库。这样做的好处是它简单且自包含(没有依赖)。

但我确实感觉到了你的问题。这就是组合解。

var http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs")
    port = process.argv[2] || 8888;

http.createServer(function(request, response) {

  var uri = url.parse(request.url).pathname
    , filename = path.join(process.cwd(), uri);

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

  fs.exists(filename, function(exists) {
    if(!exists) {
      response.writeHead(404, {"Content-Type": "text/plain"});
      response.write("404 Not Found\n");
      response.end();
      return;
    }

    if (fs.statSync(filename).isDirectory()) filename += '/index.html';

    fs.readFile(filename, "binary", function(err, file) {
      if(err) {        
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(err + "\n");
        response.end();
        return;
      }

      var headers = {};
      var contentType = contentTypesByExtension[path.extname(filename)];
      if (contentType) headers["Content-Type"] = contentType;
      response.writeHead(200, headers);
      response.write(file, "binary");
      response.end();
    });
  });
}).listen(parseInt(port, 10));

console.log("Static file server running at\n  => http://localhost:" + port + "/\nCTRL + C to shutdown");

我在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函数。这是为了允许包含空格和编码字符的文件名。

这里有很多复杂的答案。如果你不打算处理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。完成了。

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