我想运行一个非常简单的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,如果你不需要NodeJS的东西,你可以使用服务包来实现这个:

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

npm install -g serve

2 -提供静态文件夹:

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

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

http://localhost:3000

其他回答

你可以在shell中输入这些

npx serve

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

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

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

npm-free-server(在GitHub)

编辑:

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

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

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

npm install -g serve

2 -提供静态文件夹:

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

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

http://localhost:3000

最快捷的方法:

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);