通过HTTP Post将动态创建的zip流传输到服务器

时间:2019-05-30 20:30:04

标签: javascript node.js request jszip

当前,我在本地计算机上运行的nodeJS代码采用一个JSON对象,在JSON数据的本地创建一个zip文件,然后将该新创建的zip文件上传到目标Web服务。作为参数传递的JSON对象是查询数据库并将结果聚合到1个大JSON对象中的结果。

我面临的问题是我不确定如何在发出http帖子请求之前取消在本地创建zip文件的需要。

/**
    * Makes a https POST call to a specific destination endpoint to submit a form.
    * @param {string} hostname - The hostname of the destination endpoint
    * @param {string} path - The path on the destination endpoint.
    * @param {Object} formData - the form of key-value pairs to submit.
    * @param {Object} formHeaders - the headers that need to be attached to the http request.
    * @param {Object} jsonData - a large JSON Object that needs to be compressed prior to sending.
    * @param {Object} logger - a logging mechanism.
    */
    function uploadDataToServer(hostname, path, formData, formHeaders, jsonData, logger){
      var jsonData = {};// large amout of JSON Data HERE.
      var hostname = ""; // destination serverless
      var path = ""; //destination path
      let url = 'https://'+hostname+path;
      return new Promise((resolve, reject) => {
        var zip = new JSZip();
        zip.file("aggResults.json", JSON.stringify(jsonData));
        const zipFile = zip
          .generateNodeStream({type:'nodebuffer',streamFiles:true})
          .pipe(fs.createWriteStream('test.zip'))
          .on('finish', function () {
              const readStream = fs.createReadStream('test.zip');
              console.log("test.zip written.");
              request.post(url, {
                headers:formHeaders,
                formData: {
                  uploadFile:readStream
                },
              }, function (err, resp, body) {
                if (err) {
                  reject(err);
                } else {
                  resolve(body);
                }
              })
          })
      });
    }

0 个答案:

没有答案