简体   繁体   English

从 github 下载带有本机 nodejs 库的 tar 文件(节点:http,节点:fs)

[英]Download tar file from github with native nodejs libs (node:http, node:fs)

I am trying to download a tar file from a public repository using native script with get function from "node:http" and write the result data using createWriteStream function from "node:fs", but it fails.我正在尝试使用本机脚本从公共存储库下载 tar 文件,从“node:http”获取 function 并使用 createWriteStream function 从“node:fs”写入结果数据,但它失败了。 all is processed, the request return status code 301 (redirect) and the file is not downloaded, just generates an empty file.全部处理完毕,请求返回状态码301(重定向)并且文件没有下载,只是生成一个空文件。

The code:编码:


import { get } from 'node:http';
import { createWriteStream } from 'node:fs';


const out = createWriteStream('./data.tar');

// https://api.github.com/repos/4lessandrodev/nest-template/tarball/main
const request = get({
    host: 'api.github.com',
    path: '/repos/4lessandrodev/nest-template/tarball/main',
    port: 80,
    timeout: 30000,
    headers: {
        'Accept-Encoding': 'gzip, compress, deflate',
        'Content-Description': 'Get tar from github',
        'Content-Type': 'application/javascript',
        'Content-Transfer-Encoding': 'binary',
    }
});

request.on('response', (response) => {

    console.log(response.statusCode); // returns 301

    const onError = (error) => {
        if (error) {
            console.log(error);
            process.exitCode = 1;
        }
    };

    response.on('error', onError);

    response.pipe(out);

    // pipeline(response, createGunzip(), out, onError);
});


What's wrong?怎么了?

  • Import https insted http进口https装http
  • I changed the target url to redirected result我将目标 url 更改为重定向结果

import { get } from 'node:https';
import { createWriteStream } from 'node:fs';
import { URL } from 'node:url';
import { PrintError } from '@ui/print';

const out = createWriteStream('./data');
const url = new URL('https://codeload.github.com/4lessandrodev/nest-template/legacy.tar.gz/refs/heads/main');
const request = get(url);

request.on('response', (response) => {

    const status = response.statusCode;
    const message = response.statusMessage;

    if (!status || status !== 200) {
        PrintError('Error on download template', message ?? 'connection refused');
        process.exitCode = 1;
    }

    const onError = (error: any) => {
        if (error) {
            PrintError('Unexpected error', error.message);
            process.exitCode = 1;
        }
    };

    response.on('error', onError);

    response.pipe(out, { end: true });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM