我试图通过改善来发布一个原始的身体。我有接收方正确,当使用POSTman我可以发送原始zip文件,并在服务器的文件系统上正确创建该文件。但是,我很难在摩卡中写下我的考试。这是我的代码,非常感谢任何帮助。
我尝试过这种方法。
const should = require('should');
const restify = require('restify');
const fs = require('fs');
const port = 8080;
const url = 'http://localhost:' + port;
const client = restify.createJsonClient({
url: url,
version: '~1.0'
});
const testPath = 'test/assets/test.zip';
fs.existsSync(testPath).should.equal(true);
const readStream = fs.createReadStream(testPath);
client.post('/v1/deploy', readStream, function(err, req, res, data) {
if (err) {
throw new Error(err);
}
should(res).not.null();
should(res.statusCode).not.null();
should(res.statusCode).not.undefined();
res.statusCode.should.equal(200);
should(data).not.null();
should(data.endpoint).not.undefined();
data.endpoint.should.equal('http://endpointyouhit:8080');
done();
});
然而,文件系统上的文件大小始终为0.我没有正确使用我的readStream,但我不确定如何纠正它。任何帮助将不胜感激。
请注意,我想要传输文件,而不是在发送和接收时将其加载到内存中,文件可能对于内存操作而言可能太大。
谢谢, 托德
答案 0 :(得分:0)
有一点是您需要指定多部分/表单数据的内容类型。但是,它看起来像restify doesn't support that content type,所以您使用restify客户端发布文件可能会运气不佳。
答案 1 :(得分:0)
要回答我自己的问题,似乎无法使用restify客户端执行此操作。我还尝试了声称具有此功能的请求模块。但是,在使用其流式示例时,我的服务器上的文件大小始终为0。下面是一个功能性的mocha集成测试。
const testPath = 'test/assets/test.zip';
fs.existsSync(testPath).should.equal(true);
const readStream = fs.createReadStream(testPath);
var options = {
host: 'localhost'
, port: port
, path: '/v1/deploy/testvalue'
, method: 'PUT'
};
var req = http.request(options, function (res) {
//this feels a bit backwards, but these are evaluated AFTER the read stream has closed
var buffer = '';
//pipe body to a buffer
res.on('data', function(data){
buffer+= data;
});
res.on('end', function () {
should(res).not.null();
should(res.statusCode).not.null();
should(res.statusCode).not.undefined();
res.statusCode.should.equal(200);
const json = JSON.parse(buffer);
should(json).not.null();
should(json.endpoint).not.undefined();
json.endpoint.should.equal('http://endpointyouhit:8080');
done();
});
});
req.on('error', function (err) {
if (err) {
throw new Error(err);
}
});
//pipe the readstream into the request
readStream.pipe(req);
/**
* Close the request on the close of the read stream
*/
readStream.on('close', function () {
req.end();
console.log('I finished.');
});
//note that if we end up with larger files, we may want to support the continue, much as S3 does
//https://nodejs.org/api/http.html#http_event_continue