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

如何在AWS CodeArtifact JS SDK v3中指定路径下载JAR文件?

解决AWS CodeArtifact JAR文件本地下载问题

你当前的代码仅调用API获取到了文件内容,但SDK不会自动将内容写入本地文件,需要手动处理文件写入逻辑。以下是修改后的完整实现:

关键改动说明

  • 引入Node.js的fs/promises模块(异步文件操作,避免回调嵌套)
  • 在获取API响应后,将返回的asset(Buffer格式)写入指定本地路径
  • 添加错误捕获逻辑,处理API调用或文件写入时的异常

修改后的完整代码

const { CodeartifactClient, GetPackageVersionAssetCommand } = require("@aws-sdk/client-codeartifact");
const fs = require('fs/promises');
const path = require('path');

// 配置你的CodeArtifact参数
const input = {
    asset: "your-package-name-1.0.0.jar", // 要下载的JAR文件名
    domain: "your-domain",
    domainOwner: "your-account-id",
    format: "maven", // JAR对应Maven格式
    namespace: "com.yourcompany", // Maven的groupId
    package: "your-package-name", // Maven的artifactId
    packageVersion: "1.0.0",
    repository: "your-repo-name"
};

// 初始化客户端,补充AWS区域
const client = new CodeartifactClient({ region: "your-aws-region" });

const command = new GetPackageVersionAssetCommand(input);

async function getPackageAsset(command) {
    try {
        const response = await client.send(command);
        
        // 指定本地存储路径,示例为当前目录下的downloads文件夹
        const localFilePath = path.join(__dirname, 'downloads', input.asset);
        // 自动创建不存在的目录
        await fs.mkdir(path.dirname(localFilePath), { recursive: true });
        
        // 将Buffer写入本地文件
        await fs.writeFile(localFilePath, response.asset);
        console.log(`文件已成功下载到: ${localFilePath}`);
    } catch (error) {
        console.error("下载或写入文件失败:", error);
        throw error;
    }
}

getPackageAsset(command);

注意事项

  • 替换input里的所有占位符为你的实际CodeArtifact配置
  • 确保运行代码的环境有足够的文件系统写入权限
  • response.asset在Node.js环境下是Buffer类型,可直接传入fs.writeFile处理

内容的提问来源于stack exchange,提问作者Suryadeep Chatterjee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:48:30