代码之家  ›  专栏  ›  技术社区  ›  3jay1

使用NodeJS从URL下载txt文件

  •  1
  • 3jay1  · 技术社区  · 10 月前

    我想使用node从以下链接下载.txt文件:

    https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/http.txt

    并将其保存到与我的.js文件相同的目录中。

    经过一些研究,这里关于堆栈溢出的大多数答案似乎都使用了现在不推荐使用的请求方法。

    在不使用第三方库的情况下,最好的方法是什么?

    1 回复  |  直到 10 月前
        1
  •  1
  •   Amir MB    10 月前

    您可以使用 https 模块:

    const https = require('https');
    const fs = require('fs');
    const url = 'https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/http.txt';
    
    https.get(url, (response) => {
      const file = fs.createWriteStream('http.txt');
    
      response.on('data', (chunk) => {
        file.write(chunk);
      });
    
      response.on('end', () => {
        console.log('File downloaded successfully');
        file.end();
      });
    
    }).on('error', (err) => {
      console.error('Error: ', err.message);
    });