meteorjs中的imagemagick(在流星路由器和光纤的帮助下) [英] imagemagick in meteorjs (with the help of meteor-router and fibers)

查看:204
本文介绍了meteorjs中的imagemagick(在流星路由器和光纤的帮助下)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在meteorjs中使用imagemagick。我正在研究一个小的svg-> png转换器,它包含一个rest api来提供转换后的图像。我用meteor-router实现了其余的api。 imagemagick转换工作。但是,我无法将转换结果写入http响应。我试图通过使用光纤摆脱异步性来解决这个问题。但这仍然行不通。基本上,在yield执行后会忽略所有request.write调用。这是我的代码:

I am unable to use imagemagick in meteorjs. I am working on a small svg->png converter which contains a rest api to provide the converted images. I implemented the rest api with meteor-router. The imagemagick convertion works. But, I am not able to write the result of the convertion into the http response. I tried to fix this by getting rid of the asynchronisity by using fiber. But this still doesn't work. Basically, all request.write calls are ignored after the yield execution. Here is my code:

Meteor.Router.add({
  '/image/:hash' : function(hash) {

    var svg = Images.findOne({'hash' : hash}).svg;

    var request = this.request;
    var response = this.response;

    Fiber(function() {
      var fiber = Fiber.current;

      response.writeHead(200, {'Content-Type':'image/png'});

      var convert = imagemagick.convert(['svg:-', 'png:-']);

      convert.on('data', function(data) {
        response.write("doesn't work");
        //response.write(data);
      });

      convert.on('end', function() {
        response.write("doesn't work");
        //response.end();
        fiber.run({});
      });

      convert.stdin.write(svg);
      convert.stdin.end();

      response.write("works");
      Fiber.yield();
      response.write("doesn't work");
    }).run();

  }
});

我对meteorjs很新。因此,我可能会使用光纤完全错误。或者我根本不应该使用光纤。有人可以帮忙吗?

I am pretty new to meteorjs. Therefore, I might use Fiber completely wrong. Or I should not use fiber at all. Can someone help?

推荐答案

感谢meteor-router的作者,我能够解决问题。我错误地使用光纤。如 https://github.com/laverdet/node-fibers#futures 所述,建议不要在代码和原始API之间使用光纤。

Thanks to the author from meteor-router, I was able to fix the problem. I was using fiber the wrong way. As described at https://github.com/laverdet/node-fibers#futures, it's not recommended to use fiber without an abstraction between your code and the raw API.

幸运的是,光纤提供了一个名为future的抽象,可以用于我的用例!以下是工作代码:

Fortunately, fiber provides one abstraction called future which can be used for my use case! Here is the working code:

var require = __meteor_bootstrap__.require,
Future  = require('fibers/future');

Meteor.startup(function() {
  Meteor.Router.add('/image/:hash', function(hash) {
    var response = this.response;
    var fut = new Future();

    response.writeHead(200, {'Content-Type':'text/plain'});

    setTimeout(function(){ 
      response.write("hello hello");
      fut.ret();
    }, 1); 

    fut.wait();
  });
});

这篇关于meteorjs中的imagemagick(在流星路由器和光纤的帮助下)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆