我如何 fs.readFile() 来自 meteor-up 部署的 /public 文件夹中的文件?

How can I fs.readFile() a file from the /public folder of a meteor-up deployment?

我有一个 meteor-up/mupx 部署,在 Meteor /public 文件夹中有一个页面,./public/index.html

我可以从 url 成功加载页面,如下所示:

http://my-app.com:3333/index.html

但是我想让这个页面成为域的默认页面,这样我就可以像这样访问它:

http://my-app.com:3333/

我在我的 Meteor bootstrap.js 文件中添加了以下内容

WebApp.connectHandlers.use("/", function(req, res, next) {
  var err, error, error1, filepath0, filepath1;
  if (req.originalUrl !== '/' || req.method !== 'GET') {
    return next();
  }
  try {
    filepath0 = process.env.PWD + '/public/index.html';
    // filepath1 = '/opt/my-app/current/bundle/programs/web.browser/app/index.html';
    fs.statSync(filepath0).isFile();
  } catch (error) {
      err = error1;
      console.log("file not available, path=" + filepath);
      return next();
  }
  fs.readFile(filepath0, function(err, buf) {
    var eTag, err, headers;
    try {
      eTag = crypto.createHash('md5').update(buf).digest('hex');
      if (req.headers['if-none-match'] === eTag) {
        res.writeHead(304, 'Not Modified');
        return res.end();
      }
    } catch (err) {
      eTag = null;
    }
    headers = {
      'Content-Type': 'text/html',
      'ETag': etag
    };
    res.writeHead(200, headers);
    return res.end(buf);
  });
});

这在我的标准 Meteor 项目中运行良好。但是,当我通过 mupx 部署时,出现异常,因为 index.html 文件不在同一位置。

在通过 mupx

部署后,我如何 fs.readFile() 位于 /path/to/Meteor/public 中的文件

Meteor,我可以使用 `filepath0 = process.env.PWD + '/public/index.html'

但是来自 mupx 的相同代码给出了 filepath0 = /bundle/bundle/public/index.html,但该文件不存在。

mupx 服务器,我实际上可以 ls filepath1 处的文件,但即使使用该值也不起作用。

问题中您自己给出了答案。根据您的部署状态(开发或生产),您只需要具有正确的 URL。只需在 mupx 配置文件中设置一个新的环境变量,并在为 index.html 生成 URL 之前在 process.env 中查找它。


除了以上是解决您问题的快速而肮脏的 hack 之外,我觉得您正在以完全错误的方式处理这个问题。如果 index.html 需要成为您访问该站点时的默认页面(是的,这就是路由 '/' 的等价物),为什么它不是您的 client/main.html

如果由于某些我们不知道的原因,您无法使用客户端文件夹,只需在您的项目根目录中保留一个 main.html 并使用简单的 [=24] 将其设置为重定向到 /index.html =] 重定向。什么需要石头冷生成您自己的页面响应?!

我通过反复试验弄明白了。感谢@quirk 为我指明了正确的方向。还有,console.log(fs.readdirSync('.'))

meteor-up 部署中“/public”文件夹的路径是:

// console.log(fs.readdirSync('.')) => '/opt/my-app/current/bundle/programs/server' public_folder = '../../programs/web.browser/app' filepath = '../../programs/web.browser/app/index.html'

IronRouter 有服务器端路由。见 h/t Serving an "index.html" file in public/ when using MeteorJS and Iron Router?

这就是我为让它发挥作用所做的工作:

安装文件:

# copy /path/to/ionic/www to /path/to/meteor/public
# put ./public/index.html into ./private
cd /path/to/meteor/private; ln -s ../public/index.html .;

设置路由:

# /path/to/meteor/server/bootstrap.js
Router.route('/', {
  where: 'server'
}).get(function() {
  var contents;
  contents = Assets.getText('index.html');
  return this.response.end(contents);
});