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

Node.js下载GitHub YAML文件返回HTML内容的问题求助

解决GitHub YAML文件下载返回HTML的问题

问题核心

你使用的GitHub URL是文件预览页面(路径包含blob),这类URL返回的是GitHub网页(text/html),而非原始YAML文件。要获取原始文件,必须使用GitHub的原始文件URL。

修正方法

将GitHub URL中的blob替换为raw:

  • 原URL示例:https://github.com/bian-official/public/blob/main/release12.0.0/semantic-apis/oas3/yamls/Loan.yaml
  • 修改后:https://github.com/bian-official/public/raw/main/release12.0.0/semantic-apis/oas3/yamls/Loan.yaml

修正后的代码示例

方法1:Axios流式下载

const axios = require('axios');
const fs = require('fs');
const path = require('path');

async function downloadYamlFile(fileUrl, outputLocationPath) {
  const writer = fs.createWriteStream(outputLocationPath);

  return axios({
    method: 'get',
    url: fileUrl,
    responseType: 'stream',
  }).then(response => {
    response.data.pipe(writer);
    return new Promise((resolve, reject) => {
      writer.on('finish', resolve);
      writer.on('error', reject);
    });
  });
}

// 使用替换后的raw格式URL
const fileUrl = 'https://github.com/bian-official/public/raw/main/release12.0.0/semantic-apis/oas3/yamls/Loan.yaml';
const outputLocationPath = path.resolve(__dirname, 'file.yaml');

downloadYamlFile(fileUrl, outputLocationPath)
  .then(() => console.log('YAML文件下载成功'))
  .catch(error => console.error('下载失败:', error));

方法2:Fetch获取内容并保存

const express = require('express');
const bodyParser = require('body-parser');
const fetch = require('node-fetch');
const fs = require('fs');
const path = require('path');

const app = express();
const port = 5000;

app.use(bodyParser.json());

app.post('/generate-code', async (req, res) => {
  // 自动将blob URL转换为raw URL
  let { yamlUrl } = req.body;
  yamlUrl = yamlUrl.replace('/blob/', '/raw/');

  try {
    const response = await fetch(yamlUrl);
    if (!response.ok) throw new Error(`请求失败: ${response.status}`);
    
    const yamlContent = await response.text();
    const yamlFilePath = path.join(__dirname, 'api-definition.yaml');
    fs.writeFileSync(yamlFilePath, yamlContent);

    res.status(200).json({ message: 'YAML文件已保存,可继续后续处理' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(port, () => console.log(`服务运行在端口 ${port}`));

额外说明

  • 无需额外设置Accept请求头,GitHub会自动返回text/yaml或application/x-yaml类型的原始文件内容
  • 如果需要批量处理多个URL,可以封装一个简单的替换函数自动转换blob路径为raw

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 07:52:46