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


当前回答

我对这一页上的任何答案都没有太多的运气,然而,下面的答案似乎起了作用。

添加包含以下内容的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)

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

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

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

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

其他回答

你可以试着为我服务

使用它非常简单:

ServeMe = require('serve-me')();
ServeMe.start(3000);

仅此而已。

PD:默认情况下提供的文件夹为“public”。

使用connect的简单静态服务器

var connect = require('connect'),
  directory = __dirname,
  port = 3000;

connect()
  .use(connect.logger('dev'))
  .use(connect.static(directory))
  .listen(port);

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

另请参见将node.js用作简单的web服务器

NPM上还没有,但我在Express上构建了一个简单的静态服务器,它还允许您接受表单提交,并通过事务电子邮件服务(现在是Sendgrid,Mandrill即将到来)发送电子邮件。

https://github.com/jdr0dn3y/nodejs-StatServe

如果您对超轻http服务器感兴趣,无需任何先决条件你应该看看:猫鼬

#仅演示/原型服务器

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

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>`
}