使用 node.js 作为简单的 Web 服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6084360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using node.js as a simple web server
提问by idophir
I want to run a very simple HTTP server. Every GET request to example.comshould get index.htmlserved to it but as a regular HTML page (i.e., same experience as when you read normal web pages).
我想运行一个非常简单的 HTTP 服务器。每个 GET 请求都example.com应该index.html作为一个普通的 HTML 页面提供给它(即,与您阅读普通网页时的体验相同)。
Using the code below, I can read the content of index.html. How do I serve index.htmlas a regular web page?
使用下面的代码,我可以阅读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);
One suggestion below is complicated and requires me to write a getline for each resource (CSS, JavaScript, images) file I want to use.
下面的一个建议很复杂,需要我为get我想要使用的每个资源(CSS、JavaScript、图像)文件写一行。
How can I serve a single HTML page with some images, CSS and JavaScript?
如何使用一些图像、CSS 和 JavaScript 为单个 HTML 页面提供服务?
回答by Tony O'Hagan
Simplest Node.js server is just:
最简单的 Node.js 服务器就是:
$ npm install http-server -g
Now you can run a server via the following commands:
现在您可以通过以下命令运行服务器:
$ cd MyApp
$ http-server
If you're using NPM 5.2.0 or newer, you can use http-serverwithout installing it with npx. This isn't recommended for use in production but is a great way to quickly get a server running on localhost.
如果您使用的是 NPM 5.2.0 或更高版本,则http-server无需安装npx. 不建议在生产中使用它,但它是快速让服务器在 localhost 上运行的好方法。
$ npx http-server
Or, you can try this, which opens your web browser and enables CORS requests:
或者,您可以尝试此操作,它会打开您的 Web 浏览器并启用 CORS 请求:
$ http-server -o --cors
For more options, check out the documentation for http-serveron GitHub, or run:
有关更多选项,请查看GitHub 上的文档http-server,或运行:
$ http-server --help
Lots of other nice features and brain-dead-simple deployment to NodeJitsu.
许多其他不错的功能和对 NodeJit 的简单部署。
Feature Forks
功能叉
Of course, you can easily top up the features with your own fork. You might find it's already been done in one of the existing 800+ forks of this project:
当然,您可以使用自己的分叉轻松地充值功能。您可能会发现它已经在该项目现有的 800 多个分支之一中完成:
Light Server: An Auto Refreshing Alternative
Light Server:自动刷新的替代方案
A nice alternative to http-serveris light-server. It supports file watching and auto-refreshing and many other features.
一个不错的替代方案http-server是light-server. 它支持文件监视和自动刷新以及许多其他功能。
$ npm install -g light-server
$ light-server
Add to your directory context menu in Windows Explorer
添加到 Windows 资源管理器中的目录上下文菜单
reg.exe add HKCR\Directory\shell\LightServer\command /ve /t REG_EXPAND_SZ /f /d "\"C:\nodejs\light-server.cmd\" \"-o\" \"-s\" \"%V\""
Simple JSON REST server
简单的 JSON REST 服务器
If you need to create a simple REST server for a prototype project then json-servermight be what you're looking for.
如果您需要为原型项目创建一个简单的 REST 服务器,那么json-server可能就是您要找的。
Auto Refreshing Editors
自动刷新编辑器
Most web page editors and IDE tools now include a web server that will watch your source files and auto refresh your web page when they change.
大多数网页编辑器和 IDE 工具现在都包含一个 Web 服务器,该服务器将监视您的源文件并在它们更改时自动刷新您的网页。
I use Live Serverwith Visual Studio Code.
我将Live Server与 Visual Studio Code 一起使用。
The open sourcetext editor Bracketsalso includes a NodeJS static web server. Just open any HTML file in Brackets, press "Live Preview" and it starts a static server and opens your browser at the page. The browser will **auto refresh whenever you edit and save the HTML file. This especially useful when testing adaptive web sites. Open your HTML page on multiple browsers/window sizes/devices. Save your HTML page and instantly see if your adaptive stuff is working as they allauto refresh.
在开源的文本编辑器支架还包括一个静态的NodeJS web服务器。只需在 Brackets 中打开任何 HTML 文件,按“实时预览”,它就会启动一个静态服务器并在页面上打开您的浏览器。每当您编辑和保存 HTML 文件时,浏览器都会**自动刷新。这在测试自适应网站时特别有用。在多个浏览器/窗口大小/设备上打开您的 HTML 页面。保存您的 HTML 页面并立即查看您的自适应内容是否正常工作,因为它们都会自动刷新。
PhoneGap Developers
PhoneGap 开发人员
If you're coding a hybrid mobile app, you may be interested to know that the PhoneGapteam took this auto refresh concept on board with their new PhoneGap App. This is a generic mobile app that can load the HTML5 files from a server during development. This is a very slick trick since now you can skip the slow compile/deploy steps in your development cycle for hybrid mobile apps if you're changing JS/CSS/HTML files — which is what you're doing most of the time. They also provide the static NodeJS web server (run phonegap serve) that detects file changes.
如果您正在编写混合移动应用程序,您可能有兴趣知道PhoneGap团队在他们的新PhoneGap 应用程序中采用了这种自动刷新概念。这是一个通用的移动应用程序,可以在开发过程中从服务器加载 HTML5 文件。这是一个非常巧妙的技巧,因为现在如果您正在更改 JS/CSS/HTML 文件,您可以跳过混合移动应用程序开发周期中缓慢的编译/部署步骤——这是您大部分时间所做的事情。它们还提供phonegap serve检测文件更改的静态 NodeJS Web 服务器 (run )。
PhoneGap + Sencha Touch Developers
PhoneGap + Sencha Touch 开发者
I've now extensively adapted the PhoneGap static server & PhoneGap Developer App for Sencha Touch & jQuery Mobile developers. Check it out at Sencha Touch Live. Supports --qr QR Codes and --localtunnel that proxies your static server from your desktop computer to a URL outside your firewall! Tons of uses. Massive speedup for hybrid mobile devs.
我现在已经为 Sencha Touch 和 jQuery Mobile 开发人员广泛地调整了 PhoneGap 静态服务器和 PhoneGap 开发人员应用程序。在Sencha Touch Live 上查看。支持 --qr 二维码和 --localtunnel 将您的静态服务器从台式计算机代理到防火墙外的 URL!吨用途。混合移动开发者的大规模加速。
Cordova + Ionic Framework Developers
Cordova + Ionic 框架开发人员
Local server and auto refresh features are baked into the ionictool. Just run ionic servefrom your app folder. Even better ... ionic serve --labto view auto-refreshing side by side views of both iOS and Android.
本地服务器和自动刷新功能已融入该ionic工具中。只需ionic serve从您的应用程序文件夹运行。更好的是......ionic serve --lab查看iOS和Android的自动刷新并排视图。
回答by Gian Marco Gherardi
You can use Connectand ServeStaticwith Node.js for this:
您可以将Connect和ServeStatic与 Node.js 结合使用:
Install connect and serve-static with NPM
$ npm install connect serve-staticCreate server.js file with this content:
var connect = require('connect'); var serveStatic = require('serve-static'); connect() .use(serveStatic(__dirname)) .listen(8080, () => console.log('Server running on 8080...'));Run with Node.js
$ node server.js
使用 NPM 安装连接和静态服务
$ npm install connect serve-static使用以下内容创建 server.js 文件:
var connect = require('connect'); var serveStatic = require('serve-static'); connect() .use(serveStatic(__dirname)) .listen(8080, () => console.log('Server running on 8080...'));使用 Node.js 运行
$ node server.js
You can now go to http://localhost:8080/yourfile.html
你现在可以去 http://localhost:8080/yourfile.html
回答by Jonathan Tran
Check out this gist. I'm reproducing it here for reference, but the gist has been regularly updated.
看看这个要点。我在这里复制以供参考,但要点已定期更新。
Node.JS static file web server. Put it in your path to fire up servers in any directory, takes an optional port argument.
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");
Update
更新
The gist does handle css and js files. I've used it myself. Using read/write in "binary" mode isn't a problem. That just means that the file isn't interpreted as text by the file library and is unrelated to content-type returned in the response.
要点确实处理 css 和 js 文件。我自己用过。在“二进制”模式下使用读/写不是问题。这只是意味着文件不会被文件库解释为文本,并且与响应中返回的内容类型无关。
The problem with your code is you're always returning a content-type of "text/plain". The above code does not return any content-type, but if you're just using it for HTML, CSS, and JS, a browser can infer those just fine. No content-type is better than a wrong one.
您的代码的问题是您总是返回“文本/纯文本”的内容类型。上面的代码不返回任何内容类型,但如果你只是将它用于 HTML、CSS 和 JS,浏览器可以很好地推断出它们。没有内容类型比错误的内容类型更好。
Normally the content-type is a configuration of your web server. So I'm sorry if this doesn't solve yourproblem, but it worked for me as a simple development server and thought it might help some other people. If you do need correct content-types in the response, you either need to explicitly define them as joeytwiddle has or use a library like Connect that has sensible defaults. The nice thing about this is that it's simple and self-contained (no dependencies).
通常,内容类型是您的 Web 服务器的配置。因此,如果这不能解决您的问题,我很抱歉,但它作为一个简单的开发服务器对我有用,并认为它可能会帮助其他一些人。如果您在响应中确实需要正确的内容类型,您要么需要像 joeytwiddle 那样明确定义它们,要么使用像 Connect 这样具有合理默认值的库。这样做的好处是它简单且自包含(无依赖关系)。
But I do feel your issue. So here is the combined solution.
但我确实感觉到你的问题。所以这是组合解决方案。
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");
回答by B T
You don't need express. You don't need connect. Node.js does http NATIVELY. All you need to do is return a file dependent on the request:
你不需要快递。你不需要连接。Node.js 原生地执行 http。您需要做的就是根据请求返回一个文件:
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)
A more full example that ensures requests can't access files underneath a base-directory, and does proper error handling:
一个更完整的示例,可确保请求无法访问基目录下的文件,并进行正确的错误处理:
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)
回答by clee
I think the part you're missing right now is that you're sending:
我认为您现在缺少的部分是您正在发送:
Content-Type: text/plain
If you want a web browser to render the HTML, you should change this to:
如果您希望 Web 浏览器呈现 HTML,则应将其更改为:
Content-Type: text/html
回答by STEEL
Step1 (inside command prompt [I hope you cd TO YOUR FOLDER]) : npm install express
步骤 1(在命令提示符内 [我希望你 cd 到你的文件夹]): npm install express
Step 2: Create a file server.js
第 2 步:创建文件 server.js
var fs = require("fs");
var host = "127.0.0.1";
var port = 1337;
var express = require("express");
var app = express();
app.use(express.static(__dirname + "/public")); //use static files in ROOT/public folder
app.get("/", function(request, response){ //root dir
response.send("Hello!!");
});
app.listen(port, host);
Please note, you should add WATCHFILE (or use nodemon) too. Above code is only for a simple connection server.
请注意,您也应该添加 WATCHFILE(或使用 nodemon)。以上代码仅适用于简单的连接服务器。
STEP 3: node server.jsor nodemon server.js
第 3 步:node server.js或nodemon server.js
There is now more easy method if you just want host simple HTTP server.
npm install -g http-server
如果您只想托管简单的 HTTP 服务器,现在有更简单的方法。
npm install -g http-server
and open our directory and type http-server
并打开我们的目录并输入 http-server
回答by Frank Nocke
The fast way:
快捷方式:
var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/../public')); // ← adjust
app.listen(3000, function() { console.log('listening'); });
Your way:
你的方式:
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);
回答by joeytwiddle
Rather than dealing with a switch statement, I think it's neater to lookup the content type from a dictionary:
与其处理 switch 语句,我认为从字典中查找内容类型更简洁:
var contentTypesByExtension = {
'html': "text/html",
'js': "text/javascript"
};
...
var contentType = contentTypesByExtension[fileExtension] || 'text/plain';
回答by tomet
This is basically an updated version of the accepted answer for connect version 3:
这基本上是已接受的连接版本 3 答案的更新版本:
var connect = require('connect');
var serveStatic = require('serve-static');
var app = connect();
app.use(serveStatic(__dirname, {'index': ['index.html']}));
app.listen(3000);
I also added a default option so that index.html is served as a default.
我还添加了一个默认选项,以便将 index.html 作为默认选项。
回答by Jaredcheeda
You don't need to use any NPM modules to run a simple server, there's a very tiny library called "NPM Free Server" for Node:
你不需要使用任何 NPM 模块来运行一个简单的服务器,Node有一个名为“ NPM Free Server”的非常小的库:
50 lines of code, outputs if you are requesting a file or a folder and gives it a red or green color if it failed for worked. Less than 1KB in size (minified).
50 行代码,如果您请求文件或文件夹,则输出,如果工作失败,则将其显示为红色或绿色。小于 1KB(缩小)。

