You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用NodeJS创建Gzip压缩JSON文件并上传至S3存储桶?

解决Gzip压缩JSON上传S3的问题

我看了你的代码,问题核心很明确:你只是把JSON转成了Buffer,但完全没做Gzip压缩就上传了! 虽然你设置了ContentEncoding: 'gzip',但Body里的内容是未压缩的原始JSON,这会导致S3和后续消费服务识别混乱,自然达不到你想要的效果。

下面是修正后的方案,分两种实现方式:

方式一:同步压缩(适合小体积JSON)

先确保你引入了zlib模块,然后用zlib.gzipSync直接生成压缩后的Buffer:

var zlib = require('zlib'); // 必须引入zlib模块

var uploadEntitlementDataOnS3 = function(next, event, jsonFileContent, filePath, results) {
    console.log("uploadEntitlementDataOnS3 function started", jsonFileContent);
    
    // 1. 把JSON转为字符串,再转成Buffer后做Gzip压缩
    const jsonString = JSON.stringify(jsonFileContent);
    const compressedBuffer = zlib.gzipSync(Buffer.from(jsonString));
    
    var s3 = new AWS.S3();
    var params = {
        Bucket: configurationHolder.config.bucketName,
        Key: filePath,
        Body: compressedBuffer, // 替换为压缩后的Buffer
        CacheControl: 'no-cache',
        ContentType: "application/json",
        ContentEncoding: 'gzip' // 保留这个头,告诉服务端/客户端内容是gzip格式
    };
    
    s3.putObject(params, function(err, data) {
        if (err) {
            console.log(err, err.stack);
            next(err);
        } else {
            next(null, filePath);
        }
    });
};

方式二:异步压缩(适合大体积JSON,避免阻塞事件循环)

如果你的JSON数据量较大,推荐用异步版本的zlib.gzip,防止同步操作阻塞Node.js的事件循环:

var zlib = require('zlib');

var uploadEntitlementDataOnS3 = function(next, event, jsonFileContent, filePath, results) {
    console.log("uploadEntitlementDataOnS3 function started", jsonFileContent);
    
    const jsonString = JSON.stringify(jsonFileContent);
    const inputBuffer = Buffer.from(jsonString);
    
    // 异步执行Gzip压缩
    zlib.gzip(inputBuffer, function(gzipErr, compressedBuffer) {
        if (gzipErr) {
            console.log("Gzip压缩失败:", gzipErr);
            next(gzipErr);
            return;
        }
        
        var s3 = new AWS.S3();
        var params = {
            Bucket: configurationHolder.config.bucketName,
            Key: filePath,
            Body: compressedBuffer,
            CacheControl: 'no-cache',
            ContentType: "application/json",
            ContentEncoding: 'gzip'
        };
        
        s3.putObject(params, function(err, data) {
            if (err) {
                console.log(err, err.stack);
                next(err);
            } else {
                next(null, filePath);
            }
        });
    });
};

关键注意点

  • 一定要引入zlib模块,你的原代码里没有这个引入,这也是问题的诱因之一
  • ContentEncoding: 'gzip'必须和实际的压缩内容匹配,否则客户端下载后无法正确解压
  • 验证压缩是否成功:上传后可以手动下载文件,用gzip解压工具查看是否能还原为正常的JSON

内容的提问来源于stack exchange,提问作者Ankit Uniyal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:10:16