如何通过REST API读取Feat.js文件?

时间:2016-12-07 14:10:41

标签: javascript node.js rest fs feathersjs

我的应用程序在端口3030上工作正常。我创建了一个名为" config"我尝试通过REST API显示内容文件:我在此服务的文件中更改了默认的GET方法,如下所示:

'use strict';

const hooks = require('./hooks');
const fs = require('fs');
const path = require('path');
const filename = path.join(__dirname, '..', '..', '..', 'public');

class Service {
  constructor(options) {
    this.options = options || {};
  }

  find(params) {
    return Promise.resolve([]);
  }

  get(id, params) {
    var file = fs.readFileSync(filename + '/player/' + id + '/config.txt', 'utf8', (err, data) => {
      if (err) throw err;
      var json = JSON.parse(data);
      return Promise.resolve(json);
    });
  }

  create(data, params) {
    if(Array.isArray(data)) {
      return Promise.all(data.map(current => this.create(current)));
    }
    return Promise.resolve(data);
  }

  update(id, data, params) {
    return Promise.resolve(data);
  }

  patch(id, data, params) {
    return Promise.resolve(data);
  }

  remove(id, params) {
    return Promise.resolve({ id });
  }
}

module.exports = function() {
  const app = this;

  // Initialize our service with any options it requires
  app.use('/configs', new Service());

  // Get our initialize service to that we can bind hooks
  const configService = app.service('/configs');

  // Set up our before hooks
  configService.before(hooks.before);

  // Set up our after hooks
  configService.after(hooks.after);
};

module.exports.Service = Service;

我没有收到错误但却无法正常工作。在我的页面打开网址http://127.0.0.1/configs/80866后,所有时间都在加载。有什么问题?

1 个答案:

答案 0 :(得分:1)

您正在调用readFileSync同步读取文件但传递异步回调(可能永远不会被调用)。您在该回调中返回Promise但不在service方法中。 get必须如下所示:

get(id, params) {
    return new Promise((resolve, reject) => {
      const file = path.join(filename, 'player', id, config.txt);

      fs.readFile(file, (error, data) => {
        if(error) {
          return reject(error);
        }

        const json = JSON.parse(data.toString());

        resolve(json);
      });
    });
  }