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

查看:270
本文介绍了如何使用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 请求并将其响应传递到可写文件流中:

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

const http = require('http');
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天全站免登陆