协慌网

登录 贡献 社区

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

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

例如,如果我有

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

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

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

为什么我的节点静态文件服务器删除请求?引用一些神秘的东西

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

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

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

答案

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

npm install http-server -g

要使用它:

cd D:\Folder
http-server

或者,像这样:

http-server D:\Folder

签出: https://github.com/nodeapps/http-server

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

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

更新

正如 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}`);

对于希望从 NodeJS 脚本中运行服务器的用户:

您可以使用expressjs / serve-static代替connect.static (从 connect 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);

然后从命令行:

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