是否有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中的基本静态文件服务器


当前回答

您还问了为什么请求会下降-不确定具体原因是什么,但总体而言,您可以使用专用中间件(nginx、S3、CDN)更好地服务静态内容,因为Node确实没有针对这种网络模式进行优化。请参阅此处的进一步说明(项目13):http://goldbergyoni.com/checklist-best-practice-of-node-js-in-production/

其他回答

对于开发工作,您可以使用(express 4)https://github.com/appsmatics/simple-httpserver.git

我在工作和个人项目中使用休斯顿,这对我来说很好。

https://github.com/alejandro/Houston

为了搜索者的利益,我喜欢Jakub g的答案,但需要一点错误处理。显然,正确处理错误是最好的,但这有助于防止站点在发生错误时停止。代码如下:

var http = require('http');
var express = require('express');

process.on('uncaughtException', function(err) {
  console.log(err);
});

var server = express();

server.use(express.static(__dirname));

var port = 10001;
server.listen(port, function() { 
    console.log('listening on port ' + port);     
    //var err = new Error('This error won't break the application...')
    //throw err
});

在NPM注册表中搜索https://npmjs.org/search?q=server,我找到了静态服务器https://github.com/maelstrom/static-server

曾经需要向同事发送文件,但不必麻烦发送电子邮件100MB的野兽?想要运行一个简单的JavaScript示例应用程序,但在文件中运行时遇到问题:///协议希望在没有设置Samba、FTP或其他需要您编辑的内容配置文件?然后这个文件服务器会让你的生活简单一点。要安装简单的静态素材服务器,请使用npm:npm安装-g静态服务器然后,要提供文件或目录,只需运行$serve路径/to/stuff在端口8001上提供路径/到/填充

这甚至可以列出文件夹内容。

很遗憾,它无法提供文件:)

#仅演示/原型服务器

如果您只需要这些,请尝试以下操作:

const fs = require('fs'),
      http = require('http'),
      arg = process.argv.slice(2),
      rootdir = arg[0] || process.cwd(),
      port = process.env.PORT || 9000,
      hostname = process.env.HOST || '127.0.0.1';
//tested on node=v10.19.0
http.createServer(function (req, res) {

  try {
    // change 'path///to/////dir' -> 'path/to/dir'
    req_url = decodeURIComponent(req.url).replace(/\/+/g, '/');

    stats = fs.statSync(rootdir + req_url);

    if (stats.isFile()) {
      buffer = fs.createReadStream(rootdir + req_url);
      buffer.on('open', () => buffer.pipe(res));
      return;
    }

    if (stats.isDirectory()) {
      //Get list of files and folder in requested directory
      lsof = fs.readdirSync(rootdir + req_url, {encoding:'utf8', withFileTypes:false});
      // make an html page with the list of files and send to browser
      res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
      res.end(html_page(`http://${hostname}:${port}`, req_url, lsof));
      return;
    }

  } catch (err) {
      res.writeHead(404);
      res.end(err);
      return;
  }
}).listen(port, hostname, () => console.log(`Server running at http://${hostname}:${port}`));


function html_page(host, req_url, lsof) {//this is a Function declarations can be called before it is defined
  // Add link to root directory and parent directory if not already in root directory
  list = req_url == '/' ? [] : [`<a href="${host}">/</a>`,
  `<a href="${host}${encodeURI(req_url.slice(0,req_url.lastIndexOf('/')))}">..</a>`];

  templete = (host, req_url, file) => {// the above is a Function expressions cannot be called before it is defined
    return `<a href="${host}${encodeURI(req_url)}${req_url.slice(-1) == '/' ? '' : '/'}${encodeURI(file)}">${file}</a>`; }

  // Add all the links to the files and folder in requested directory
  lsof.forEach(file => {
    list.push(templete(host, req_url, file));
  });

  return `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="content-type" content="text/html" charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Directory of ${req_url}</title>
</head>
<body>
<h2>Directory of ${req_url}</h2>
${list.join('<br/>\n')}
</body>
</html>`
}