Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a file with Node.js (without using third-party libraries)?

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

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.

like image 926
greepow Avatar asked Aug 14 '12 02:08

greepow


People also ask

Can you write text in NodeJS without an external library?

However, one thing makes Node. js unique: you can write applications in Node. js without the use of external libraries.

What is third party library in NodeJS?

Node 3rd party modules is a module or package which is developed and manitained by 3rd parties. Millions of 3rd party node modules/packages which are freely available on NPM Registry. You can install node 3rd party modules/packages and use them to add functionality to your projects.


1 Answers

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

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.

like image 100
Michelle Tilley Avatar answered Oct 23 '22 21:10

Michelle Tilley