node.js – 如何停止流到承诺更改我的原始缓冲区

我正在使用stream-to-promise npm模块在我的jasmine测试中创建multipart / form-data有效负载.我的有效负载包括一个图像文件作为缓冲区,但当有效负载通过流到承诺时,它会以某种方式更改或破坏有效负载中的原始图像缓冲区,因此我的测试失败.有办法防止这种情况吗?

  it('test /identity-verification/your-first-form-of-id POST with validation passing', function(done){
    var form = new FormData();
    var image = fs.createReadStream("image.png");
    streamToBuffer(image, function (err, buffer) {
      form.append('firstID', 'passport');
      form.append('firstIDImage', buffer);
      var headers = form.getHeaders();
      streamToPromise(form).then(function(payload) {
        var options = {
          method: 'POST',
          url: '/identity-verification/your-first-form-of-id',
          payload: payload,
          headers: headers
        };
        server.inject(options, function(response) {
          expect(response.statusCode).toBe(302);
          expect(response.headers.location).toMatch('/identity-verification/your-first-form-of-id/upload-successful');
          done();
        });
      });
    });
  });

通过流到承诺后,有效负载中的缓冲区如下所示:

最佳答案 您不需要流到缓冲区.你已经从createReadStream获得了缓冲区.如果你摆脱它,它应该工作.有一点需要注意的是,你的maxBytes设置得足够高,可以容纳你的测试图像.这在我测试时引起了一些神秘的错误.

下面的代码对我来说很好.

 var streamToPromise = require("stream-to-promise");
 var FormData = require("form-data");
 var fileTypeModule = require("file-type");
 var fs = require("fs");
 var q = require("q");
 var Hapi = require('hapi');
 var server = new Hapi.Server({ debug: { request: ['error'] } });

 server.connection({
     host: 'localhost',
     port: 8000
 });

 server.route({
     method: 'POST',
     path: '/test',
     handler: function(request, reply) {
         var data = request.payload.firstIDImage;
         var fileType = fileTypeModule(data);
         reply(fileType);
     },
     config: {
         payload: { maxBytes: 1048576 }
     }
 });

 var start = server.start();
 var form = new FormData();
 var headers = form.getHeaders();

 form.append('firstID', 'passport');
 form.append('firstIDImage', fs.createReadStream("image.png"));
 var append = streamToPromise(form);
 q.all([start, append]).then((results) => {
     var options = {
         method: 'POST',
         url: '/test',
         payload: results[1],
         headers: headers
     };
     server.inject(options, function(response) {
        console.log(response.payload);
     });
 });
点赞