Node.js 快速文件服务器(HTTP 上的静态文件)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16333790/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:23:44  来源:igfitidea点击:

Node.js quick file server (static files over HTTP)

node.jshttpfileserver

提问by Paul Verest

Is there Node.js ready-to-use tool (installed with npm), that would help me expose folder content as file server over HTTP.

是否有 Node.js 即用型工具(随 一起安装npm),这将帮助我通过 HTTP 将文件夹内容公开为文件服务器。

Example, if I have

例如,如果我有

D:\Folder\file.zip
D:\Folder\file2.html
D:\Folder\folder\file-in-folder.jpg

Then starting in D:\Folder\node node-file-server.jsI could access file via

然后开始D:\Folder\node node-file-server.js我可以通过访问文件

http://hostname/file.zip
http://hostname/file2.html
http://hostname/folder/file-in-folder.jpg

Why is my node static file server dropping requests?reference some mystical

为什么我的节点静态文件服务器丢弃请求?参考一些神秘的

standard node.js static file server

标准 node.js 静态文件服务器

If there's no such tool, what framework should I use?

如果没有这样的工具,我应该使用什么框架?

Related: Basic static file server in NodeJS

相关: NodeJS 中的基本静态文件服务器

回答by Matt Self

A good "ready-to-use tool" option could be http-server:

一个好的“即用型工具”选项可能是 http-server:

npm install http-server -g

To use it:

要使用它:

cd D:\Folder
http-server

Or, like this:

或者,像这样:

http-server D:\Folder

Check it out: https://github.com/nodeapps/http-server

看看:https: //github.com/nodeapps/http-server

回答by Hasan A Yousef

If you do not want to use ready tool, you can use the code below, as demonstrated by me at https://developer.mozilla.org/en-US/docs/Node_server_without_framework:

如果你不想使用现成的工具,你可以使用下面的代码,正如我在https://developer.mozilla.org/en-US/docs/Node_server_without_framework所演示的:

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

http.createServer(function (request, response) {
    console.log('request starting...');

    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.html';

    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
        case '.json':
            contentType = 'application/json';
            break;
        case '.png':
            contentType = 'image/png';
            break;      
        case '.jpg':
            contentType = 'image/jpg';
            break;
        case '.wav':
            contentType = 'audio/wav';
            break;
    }

    fs.readFile(filePath, function(error, content) {
        if (error) {
            if(error.code == 'ENOENT'){
                fs.readFile('./404.html', function(error, content) {
                    response.writeHead(200, { 'Content-Type': contentType });
                    response.end(content, 'utf-8');
                });
            }
            else {
                response.writeHead(500);
                response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
                response.end(); 
            }
        }
        else {
            response.writeHead(200, { 'Content-Type': contentType });
            response.end(content, 'utf-8');
        }
    });

}).listen(8125);
console.log('Server running at http://127.0.0.1:8125/');

UPDATEIf you need to access your server from external demand/file, you need to overcome the CORS, in your node.js file by writing the below, as I mentioned in a previous answer here

UPDATE如果您需要从外部需求/文件访问您的服务器,你需要通过编写下面,正如我在前面的回答中提到,克服了CORS,在你的Node.js文件在这里

// Website you wish to allow to connect
response.setHeader('Access-Control-Allow-Origin', '*');

// Request methods you wish to allow
response.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

// Request headers you wish to allow
response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
response.setHeader('Access-Control-Allow-Credentials', true);

UPDATE

更新

As Adrian mentioned, in the comments, he wrote an ES6 code with full explanation here, I just re-posting his code below, in case the code gone from the original site for any reason:

正如 Adrian 提到的,在评论中,他在这里写了一个完整的解释的 ES6 代码,我只是在下面重新发布他的代码,以防代码因任何原因从原始网站上消失:

const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const port = process.argv[2] || 9000;

http.createServer(function (req, res) {
  console.log(`${req.method} ${req.url}`);

  // parse URL
  const parsedUrl = url.parse(req.url);
  // extract URL path
  let pathname = `.${parsedUrl.pathname}`;
  // based on the URL path, extract the file extention. e.g. .js, .doc, ...
  const ext = path.parse(pathname).ext;
  // maps file extention to MIME typere
  const map = {
    '.ico': 'image/x-icon',
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.json': 'application/json',
    '.css': 'text/css',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.wav': 'audio/wav',
    '.mp3': 'audio/mpeg',
    '.svg': 'image/svg+xml',
    '.pdf': 'application/pdf',
    '.doc': 'application/msword'
  };

  fs.exists(pathname, function (exist) {
    if(!exist) {
      // if the file is not found, return 404
      res.statusCode = 404;
      res.end(`File ${pathname} not found!`);
      return;
    }

    // if is a directory search for index file matching the extention
    if (fs.statSync(pathname).isDirectory()) pathname += '/index' + ext;

    // read file from file system
    fs.readFile(pathname, function(err, data){
      if(err){
        res.statusCode = 500;
        res.end(`Error getting the file: ${err}.`);
      } else {
        // if the file is found, set Content-type and send data
        res.setHeader('Content-type', map[ext] || 'text/plain' );
        res.end(data);
      }
    });
  });


}).listen(parseInt(port));

console.log(`Server listening on port ${port}`);

回答by jakub.g

For people wanting a server runnable from within NodeJS script:

对于想要从 NodeJS 脚本中运行服务器的人:

You can use expressjs/serve-staticwhich replaces connect.static(which is no longer available as of connect 3):

您可以使用expressjs/serve-static替换connect.static(从连接 3 开始不再可用):

myapp.js:

myapp.js:

var http = require('http');

var finalhandler = require('finalhandler');
var serveStatic = require('serve-static');

var serve = serveStatic("./");

var server = http.createServer(function(req, res) {
  var done = finalhandler(req, res);
  serve(req, res, done);
});

server.listen(8000);

and then from command line:

然后从命令行:

  • $ npm install finalhandler serve-static
  • $ node myapp.js
  • $ npm install finalhandler serve-static
  • $ node myapp.js

回答by Matt Sergeant

I know it's not Node, but I've used Python's SimpleHTTPServer:

我知道它不是 Node,但我使用过 Python 的 SimpleHTTPServer:

python -m SimpleHTTPServer [port]

It works well and comes with Python.

它运行良好,并带有 Python。

回答by Oleg

connectcould be what you're looking for.

连接可能是你正在寻找的。

Installed easily with:

轻松安装:

npm install connect

Then the most basic static file server could be written as:

那么最基本的静态文件服务器可以写成:

var connect = require('connect'),
    directory = '/path/to/Folder';

connect()
    .use(connect.static(directory))
    .listen(80);

console.log('Listening on port 80.');

回答by pasx

Install express using npm: https://expressjs.com/en/starter/installing.html

使用 npm 安装 express:https://expressjs.com/en/starter/installing.html

Create a file named server.js at the same level of your index.html with this content:

使用以下内容在 index.html 的同一级别创建一个名为 server.js 的文件:

var express = require('express');
var server = express();
server.use('/', express.static(__dirname + '/'));
server.listen(8080);

If you wish to put it in a different location, set the path on the third line:

如果你想把它放在不同的位置,在第三行设置路径:

server.use('/', express.static(__dirname + '/public'));

CD to the folder containing your file and run node from the console with this command:

CD 到包含您的文件的文件夹,然后使用以下命令从控制台运行节点:

node server.js

Browse to localhost:8080

浏览到本地主机:8080

回答by Qwerty

One-line? Proofs instead of promises

一条线?证明而不是承诺

enter image description here

在此处输入图片说明

The first is http-server, hs- link

第一个是http-serverhs-链接

npm i -g http-server   // install
hs C:\repos            // run with one line?? FTW!!

The second is serveby ZEIT.co - link

第二个是serveZEIT.co -链接

npm i -g serve         // install
serve C:\repos         // run with one line?? FTW!!


Following are available options, if this is what helps you decide.

以下是可用选项,如果这有助于您做出决定。

C:\Users\Qwerty>http-server --help
usage: http-server [path] [options]

options:
  -p           Port to use [8080]
  -a           Address to use [0.0.0.0]
  -d           Show directory listings [true]
  -i           Display autoIndex [true]
  -g --gzip    Serve gzip files when possible [false]
  -e --ext     Default file extension if none supplied [none]
  -s --silent  Suppress log messages from output
  --cors[=headers]   Enable CORS via the "Access-Control-Allow-Origin" header
                     Optionally provide CORS headers list separated by commas
  -o [path]    Open browser window after starting the server
  -c           Cache time (max-age) in seconds [3600], e.g. -c10 for 10 seconds.
               To disable caching, use -c-1.
  -U --utc     Use UTC time format in log messages.

  -P --proxy   Fallback proxy if the request cannot be resolved. e.g.: http://someurl.com

  -S --ssl     Enable https.
  -C --cert    Path to ssl cert file (default: cert.pem).
  -K --key     Path to ssl key file (default: key.pem).

  -r --robots  Respond to /robots.txt [User-agent: *\nDisallow: /]
  -h --help    Print this list and exit.
C:\Users\Qwerty>serve --help

  Usage: serve.js [options] [command]

  Commands:

    help  Display help

  Options:

    -a, --auth      Serve behind basic auth
    -c, --cache     Time in milliseconds for caching files in the browser
    -n, --clipless  Don't copy address to clipboard (disabled by default)
    -C, --cors      Setup * CORS headers to allow requests from any origin (disabled by default)
    -h, --help      Output usage information
    -i, --ignore    Files and directories to ignore
    -o, --open      Open local address in browser (disabled by default)
    -p, --port   Port to listen on (defaults to 5000)
    -S, --silent    Don't log anything to the console
    -s, --single    Serve single page applications (sets `-c` to 1 day)
    -t, --treeless  Don't display statics tree (disabled by default)
    -u, --unzipped  Disable GZIP compression
    -v, --version   Output the version number


If you need to watch for changes, see hostr, credit Henry Tseng's answer

如果您需要注意更改,请参阅hostr,感谢Henry Tseng 的回答

回答by Hymansonkr

DEMO/PROTO SERVER ONLY

仅限演示/原型服务器

If that's all you need, try this:

如果这就是你所需要的,试试这个:

const http = require('http');
const fs = require('fs');
const port = 3000;
const app = http.createServer((req,res) => {
    res.writeHead(200);
    if (req.url === '/') req.url = '/index.html'; // courtesy of @JosephCho
    res.end(fs.readFileSync(__dirname + req.url));
});

app.listen(port);

note: You need to use "/index.html" as part of your address ie "http://localhost:3000/index.html"

注意:您需要使用“/index.html”作为地址的一部分,即“ http://localhost:3000/index.html

回答by Samrat Debroy

There is another static web server that is quite nice: browser-sync.

还有另一个非常好的静态 Web 服务器:浏览器同步。

It can be downloaded using node package manager:

可以使用节点包管理器下载它:

npm install -g browser-sync

After installation, navigate to the project folder in the cmd prompt and just run the following:

安装后,在 cmd 提示中导航到项目文件夹并运行以下命令:

browser-sync start --server --port 3001 --files="./*"

It will start catering all the files in the current folder in the browser.

它将开始处理浏览器中当前文件夹中的所有文件。

More can be found out from BrowserSync

可以从BrowserSync 中找到更多信息

Thanks.

谢谢。

回答by FooBar

I haven't had much luck with any of the answers on this page, however, below seemed to do the trick.

我对这个页面上的任何答案都不太走运,但是,下面似乎可以解决问题。

Add a server.jsfile with the following content:

添加server.js具有以下内容的文件:

const express = require('express')
const path = require('path')
const port = process.env.PORT || 3000
const app = express()

// serve static assets normally
app.use(express.static(__dirname + '/dist'))

// handle every other route with index.html, which will contain
// a script tag to your application's JavaScript file(s).
app.get('*', function (request, response){
  response.sendFile(path.resolve(__dirname, 'dist', 'index.html'))
})

app.listen(port)
console.log("server started on port " + port)

Also make sure that you require express. Run yarn add express --saveor npm install express --savedepending on your setup (I can recommend yarnit's pretty fast).

还要确保您需要express. 运行yarn add express --savenpm install express --save取决于您的设置(我可以推荐yarn它非常快)。

You may change distto whatever folder you are serving your content is. For my simple project, I wasn't serving from any folder, so I simply removed the distfilename.

您可以更改dist为您提供内容的任何文件夹。对于我的简单项目,我没有从任何文件夹提供服务,所以我只是删除了dist文件名。

Then you may run node server.js. As I had to upload my project to a Heroku server, I needed to add the following to my package.jsonfile:

然后你可以运行node server.js. 由于我必须将我的项目上传到 Heroku 服务器,我需要将以下内容添加到我的package.json文件中:

  "scripts": {
    "start": "node server.js"
  }