英文:
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);
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论