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


当前回答

注:此答案来自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

其他回答

稍微啰嗦一点的表达式4。X版本,但它在最少的行数中提供目录列表、压缩、缓存和请求登录

var express = require('express');
var compress = require('compression');
var directory = require('serve-index');
var morgan = require('morgan'); //logging for express

var app = express();

var oneDay = 86400000;

app.use(compress());
app.use(morgan());
app.use(express.static('filesdir', { maxAge: oneDay }));
app.use(directory('filesdir', {'icons': true}))

app.listen(process.env.PORT || 8000);

console.log("Ready To serve files !")

如果你的电脑上安装了节点,你可能有NPM,如果你不需要NodeJS的东西,你可以使用服务包来实现这个:

1 -在您的PC上安装软件包:

npm install -g serve

2 -提供静态文件夹:

serve <path> 
d:> serve d:\StaticSite

它会告诉你你的静态文件夹正在被服务的端口,只需像这样导航到主机:

http://localhost:3000

这很容易,因为今天有大量的图书馆。这里的答案是功能性的。如果你想要另一个版本开始更快和简单

当然,首先要安装node.js。后:

> # module with zero dependencies
> npm install -g @kawix/core@latest 
> # change /path/to/static with your folder or empty for current
> kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express-static.js" /path/to/static

这里是“https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express-static.js”的内容(你不需要下载,我贴出来是为了了解后面的工作原理)

// you can use like this:
// kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js" /path/to/static
// kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js" 

// this will download the npm module and make a local cache
import express from 'npm://express@^4.16.4'
import Path from 'path'

var folder= process.argv[2] || "."
folder= Path.resolve(process.cwd(), folder)
console.log("Using folder as public: " + folder)

var app = express() 
app.use(express.static(folder)) 
app.listen(8181)
console.log("Listening on 8181")

从w3schools

创建一个节点服务器来服务任何被请求的文件是很容易的,你不需要为它安装任何包

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

http.createServer(function (req, res) {
  var q = url.parse(req.url, true);
  var filename = "." + q.pathname;
  fs.readFile(filename, function(err, data) {
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'});
      return res.end("404 Not Found");
    }  
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

http://localhost:8080/file.html

将从磁盘上提供file.html

上面的大多数答案都很好地描述了内容是如何被提供的。我正在寻找作为额外的目录列表,以便该目录的其他内容可以被浏览。以下是我给更多读者的解决方案:

'use strict';

var finalhandler = require('finalhandler');
var http = require('http');
var serveIndex = require('serve-index');
var serveStatic = require('serve-static');
var appRootDir = require('app-root-dir').get();
var log = require(appRootDir + '/log/bunyan.js');

var PORT = process.env.port || 8097;

// Serve directory indexes for reports folder (with icons)
var index = serveIndex('reports/', {'icons': true});

// Serve up files under the folder
var serve = serveStatic('reports/');

// Create server
var server = http.createServer(function onRequest(req, res){
    var done = finalhandler(req, res);
    serve(req, res, function onNext(err) {
    if (err)
        return done(err);
    index(req, res, done);
    })
});


server.listen(PORT, log.info('Server listening on: ', PORT));