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

Pau*_*est 583 http fileserver node.js

是否有Node.js随时可用的工具(随附npm),这将有助于我将文件夹内容作为文件服务器通过HTTP公开.

例如,如果我有

D:\Folder\file.zip
D:\Folder\file2.html
D:\Folder\folder\file-in-folder.jpg
Run Code Online (Sandbox Code Playgroud)

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

http://hostname/file.zip
http://hostname/file2.html
http://hostname/folder/file-in-folder.jpg
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Mat*_*elf 986

一个好的"随时可用的工具"选项可能是http-server:

npm install http-server -g
Run Code Online (Sandbox Code Playgroud)

要使用它:

cd D:\Folder
http-server
Run Code Online (Sandbox Code Playgroud)

或者,像这样:

http-server D:\Folder
Run Code Online (Sandbox Code Playgroud)

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

  • 我使用`http-server -a localhost -p 80` (38认同)
  • 值得检查[browser-sync](https://www.browsersync.io/),这可以或多或少地做同样的事情,但是在修改文件时还有额外的实时更新奖励. (9认同)
  • 这太棒了.我需要指定一个地址bc由于某种原因默认的0.0.0.0没有与我的开发环境合作.`http-server -a localhost`得到了dun. (8认同)
  • `--cors`连同响应头一起发送`Access-Control-Allow-Origin:*`(即在提供json文件时) (2认同)
  • `npx http-server`-npx将其转换为单行代码,可下载并运行必要的文件。 (2认同)
  • 如果您尚未全局安装“http-server”,请尝试以下操作:“npx http-server -a 0.0.0.0 -p 80”,这样与您共享同一网络的所有计算机都可以访问您的服务器。 (2认同)

Has*_*sef 173

如果您不想使用现成工具,可以使用下面的代码,如我在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/');
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

UPDATE

正如阿德里安所说,在评论中,他写了一个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}`);
Run Code Online (Sandbox Code Playgroud)

  • 该代码是否不允许通过执行类似http://127.0.0.1/../../../etc/passwd的操作来上传文件树?我认为没有检查. (12认同)
  • 如果有人对ES6 +版本感兴趣,我创建了一个处理MIME类型的静态文件服务器:https://gist.github.com/amejiarosario/53afae82e18db30dadc9bc39035778e5 (3认同)
  • 当然,`response.writeHead(200`应该是`response.writeHead(404`;) (2认同)

jak*_*b.g 77

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

您可以使用expressjs /服务静电它取代connect.static(这是不再作为连接3):

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);
Run Code Online (Sandbox Code Playgroud)

然后从命令行:

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

  • 它是`final`处理程序而不是`file` (7认同)

Mat*_*ant 53

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

python -m SimpleHTTPServer [port]
Run Code Online (Sandbox Code Playgroud)

它运行良好,并附带Python.

  • Python3等价:`python -m http.server [port]`(上面提到的是Python2) (12认同)
  • 在PHP上:`php -S localhost:8000` (5认同)

Ole*_*leg 33

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

安装方便:

npm install connect
Run Code Online (Sandbox Code Playgroud)

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

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

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

console.log('Listening on port 80.');
Run Code Online (Sandbox Code Playgroud)

  • 这在连接3中不再起作用,因为它不暴露`connect.static`; 请参阅我的[以下答复](http://stackoverflow.com/a/24575241/)进行更换 (4认同)
  • 我相信默认情况下它仍然与**express**捆绑在一起,但现在确实存在于一个单独的`require`able模块"serve-static"中. (4认同)

DHl*_*aty 19

从 npm@5.2.0npm开始,在通常的 npm 旁边开始安装一个新的二进制文件,称为npx. 所以现在,从当前目录创建静态 http 服务器的一个班轮:

npx serve
Run Code Online (Sandbox Code Playgroud)

或者

npx http-server
Run Code Online (Sandbox Code Playgroud)


pas*_*asx 17

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

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

var express = require('express');
var server = express();
server.use('/', express.static(__dirname + '/'));
server.listen(8080);
Run Code Online (Sandbox Code Playgroud)

如果您希望将其放在其他位置,请在第三行设置路径:

server.use('/', express.static(__dirname + '/public'));
Run Code Online (Sandbox Code Playgroud)

CD到包含您的文件的文件夹,并使用此命令从控制台运行节点:

node server.js
Run Code Online (Sandbox Code Playgroud)

浏览本地主机:8080


Jac*_*nkr 13

仅限演示/投影服务器

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

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);
Run Code Online (Sandbox Code Playgroud)

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

  • 不要使用同步版本。从readStream实例化创建到res的管道。 (2认同)
  • @EduardBondarenko是正确的。`const stream = fs.createReadStream(...); 只需要stream.pipe(res);` (2认同)

Qwe*_*rty 12

One-line™Proofs而不是承诺

在此输入图像描述

首先是http-server,hs- 链接

npm i -g http-server   // install
hs C:\repos            // run with one line?? FTW!!
Run Code Online (Sandbox Code Playgroud)

第二个是serveZEIT.co - 链接

npm i -g serve         // install
serve C:\repos         // run with one line?? FTW!!
Run Code Online (Sandbox Code Playgroud)

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

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

如果您需要观看的变化,看hostr,信用亨利曾雅妮的答案


mur*_*zel 11

在普通的 node.js 中:

const http = require('http')
const fs = require('fs')
const path = require('path')

process.on('uncaughtException', err => console.error('uncaughtException', err))
process.on('unhandledRejection', err => console.error('unhandledRejection', err))

const publicFolder = process.argv.length > 2 ? process.argv[2] : '.'
const port = process.argv.length > 3 ? process.argv[3] : 8080

const mediaTypes = {
  zip: 'application/zip',
  jpg: 'image/jpeg',
  html: 'text/html',
  /* add more media types */
}

const server = http.createServer(function(request, response) {
  console.log(request.method + ' ' + request.url)

  const filepath = path.join(publicFolder, request.url)
  fs.readFile(filepath, function(err, data) {
    if (err) {
      response.statusCode = 404
      return response.end('File not found or you made an invalid request.')
    }

    let mediaType = 'text/html'
    const ext = path.extname(filepath)
    if (ext.length > 0 && mediaTypes.hasOwnProperty(ext.slice(1))) {
      mediaType = mediaTypes[ext.slice(1)]
    }

    response.setHeader('Content-Type', mediaType)
    response.end(data)
  })
})

server.on('clientError', function onClientError(err, socket) {
  console.log('clientError', err)
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')
})

server.listen(port, '127.0.0.1', function() {
  console.log('? Development server is online.')
})
Run Code Online (Sandbox Code Playgroud)

这是一个简单的 node.js 服务器,它只为特定目录中的请求文件提供服务。

用法:

node server.js folder port
Run Code Online (Sandbox Code Playgroud)

folder根据server.js位置可以是绝对的或相对的。默认值是.您执行node server.js命令的目录。

port 默认为 8080,但您可以指定操作系统中可用的任何端口。

在你的情况下,我会这样做:

cd D:\Folder
node server.js
Run Code Online (Sandbox Code Playgroud)

您可以D:\Folder通过键入从浏览器浏览下的文件http://127.0.0.1:8080/somefolder/somefile.html


Sam*_*roy 8

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

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

npm install -g browser-sync
Run Code Online (Sandbox Code Playgroud)

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

browser-sync start --server --port 3001 --files="./*"
Run Code Online (Sandbox Code Playgroud)

它将开始迎合浏览器中当前文件夹中的所有文件.

可以从BrowserSync中找到更多内容

谢谢.

  • 使用Browsersync而不是其他静态服务器的优点是,只要`--files`标志指定的文件发生变化,它就会实时更新页面(nb.你不需要指定`./*` - 只有那些你希望Browsersync主动监视更新,例如``css/*.css`) (2认同)

Foo*_*Bar 7

我对本页上的任何答案都不太满意,但是,下面的方法似乎可以解决问题。

添加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)
Run Code Online (Sandbox Code Playgroud)

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

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

然后,您可以跑步node server.js。由于必须将项目上传到Heroku服务器,因此需要在package.json文件中添加以下内容:

  "scripts": {
    "start": "node server.js"
  }
Run Code Online (Sandbox Code Playgroud)


Dan*_*iel 6

如果您使用Express框架,则可以使用此功能.

要设置简单的文件服务应用,请执行以下操作:

mkdir yourapp
cd yourapp
npm install express
node_modules/express/bin/express
Run Code Online (Sandbox Code Playgroud)


Ebr*_*owi 6

是我的单文件/轻量级node.js静态文件web-server pet项目,没有依赖,我认为这是一个快速而丰富的工具,它的使用就像在Linux/Unix/macOS终端上发出此命令一样简单(安装node.js(或在Debian/Ubuntu上)时安装Android 或termuxnodejs-legacy:

curl pad.js.org | node 
Run Code Online (Sandbox Code Playgroud)

(文档上的Windows用户存在不同的命令)

它支持我认为有用的不同的东西,

  • 分层目录索引创建/服务
    • 具有不同标准的排序功能
    • 通过[多文件]拖动和拖放和文件/文本只复制,粘贴和系统剪贴板的屏幕截图贴在Chrome,Firefox和其他可能的浏览器有一些限制(可以通过命令行关闭从浏览器上传它提供的选项)
    • 文件夹/笔记创建/上传按钮
  • 为众所周知的文件类型提供正确的MIME(有可能禁用它)
  • 可以作为npm软件包和本地工具安装,或者作为Docker的永久服务进行单线程安装
  • HTTP 206文件服务(多部分文件传输),以实现更快的传输
  • 从终端和浏览器控制台上传(实际上它原本打算成为其他页面/域上浏览器的JS控制台的文件系统代理)
  • CORS下载/上传(也可以关闭)
  • 简单的HTTPS集成
  • 轻量级命令行选项,用于实现更好的安全服务:
    • 使用node.js 8上的补丁,您无需先安装即可访问这些选项:curl pad.js.org | node - -h
    • 或者首先将其作为系统全局npm包[sudo] npm install -g pad.js安装,然后使用其安装的版本来访问其选项:pad -h
    • 或者使用提供的Docker镜像,默认情况下使用相对安全的选项. [sudo] docker run --restart=always -v /files:/files --name pad.js -d -p 9090:9090 quay.io/ebraminio/pad.js

使用该工具的文件夹索引的屏幕截图

上面描述的功能主要记录在http://pad.js.org工具的主页上,我使用的一些不错的技巧也是工具源本身也提供的地方!

工具源在GitHub上,欢迎您提供反馈,功能请求和⭐s!


Die*_*des 6

您可以使用 NPM服务为此包,如果您不需要 NodeJS 的东西,它是一个快速且易于使用的工具:

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

npm install -g serve
Run Code Online (Sandbox Code Playgroud)

2 - 为您的静态文件夹提供serve <path>

d:> serve d:\StaticSite
Run Code Online (Sandbox Code Playgroud)

它将显示您的静态文件夹正在服务哪个端口,只需导航到主机,如:

http://localhost:3000
Run Code Online (Sandbox Code Playgroud)


Man*_*ddy 5

以下为我工作:

创建一个app.js包含以下内容的文件:

// app.js

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

http.createServer(function (req, res) {
  fs.readFile(__dirname + req.url, function (err,data) {
    if (err) {
      res.writeHead(404);
      res.end(JSON.stringify(err));
      return;
    }
    res.writeHead(200);
    res.end(data);
  });
}).listen(8080);
Run Code Online (Sandbox Code Playgroud)

创建一个index.html包含以下内容的文件:

Hi
Run Code Online (Sandbox Code Playgroud)

启动命令行:

cmd
Run Code Online (Sandbox Code Playgroud)

在下面运行cmd

node app.js
Run Code Online (Sandbox Code Playgroud)

转到以下 URL,在 chrome 中:

http://localhost:8080/index.html
Run Code Online (Sandbox Code Playgroud)

就这样。希望有帮助。

来源:https : //nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/