从URL使用Node JS下载一个txt文件

huangapple go评论83阅读模式
英文:

Download a txt File from a URL using Node JS

问题

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

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

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

在进行一些研究后,似乎大多数Stack Overflow上的答案都使用了现在已经弃用的request方法。

在不使用第三方库的情况下,如何最好地完成这个任务?

英文:

I would like to use node to download the .txt file from this link:

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

and save it into the same directory as my .js file.

After doing some research it seems most answers here on stack overflow use the request method which is now deprecated.

What is the best way to do this without using 3rd party libraries?

答案1

得分: 1

你可以使用 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.end();
  });

}).on('error', (err) => {
  console.error('错误:', err.message);
});
英文:

You can use https module:

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);
});

huangapple
  • 本文由 发表于 2023年7月11日 09:17:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76658181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定