如何使用 Node.js 下载文件(不使用第三方库)? [英] How to download a file with Node.js (without using third-party libraries)?

查看:36
本文介绍了如何使用 Node.js 下载文件(不使用第三方库)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用第三方库的情况下使用 Node.js 下载文件?

How do I download a file with Node.js without using third-party libraries?

我不需要任何特别的东西.我只想从给定的 URL 下载一个文件,然后将其保存到给定的目录中.

I don't need anything special. I only want to download a file from a given URL, and then save it to a given directory.

推荐答案

您可以创建一个 HTTP GET 请求并将其 response 管道传输到一个可写的文件流中:

You can create an HTTP GET request and pipe its response into a writable file stream:

const http = require('http'); // or 'https' for https:// URLs
const fs = require('fs');

const file = fs.createWriteStream("file.jpg");
const request = http.get("http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg", function(response) {
  response.pipe(file);
});

如果你想支持在命令行上收集信息——比如指定目标文件或目录,或者 URL——检查类似 指挥官.

If you want to support gathering information on the command line--like specifying a target file or directory, or URL--check out something like Commander.

这篇关于如何使用 Node.js 下载文件(不使用第三方库)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆