How to download a file with Node.js (without using third-party libraries)?
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);
// after download completed close filestream
file.on("finish", () => {
file.close();
console.log("Download Completed");
});
});
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.
More detailed explanation in https://sebhastian.com/nodejs-download-file/
How to download a .gz file with Node.js without any third party libraries
you can try this, using HTTP module for nodesJS,it looks similar to downloading any other file, just remember to mention the extension of the downloaded file when calling instead
....Here is an example:
NOTE: IF you are trying to download from an HTTPS link, use the HTTPS
module instead, its exactly the same, but just replace all the
HTTP
in the following code withHTTPS
const http = require('http');
const fs = require('fs');
//I added './' assuming that you want to download it where the server
//file is located, just change it to your desired path, followed by the
//filename and the EXTENSION
const file = fs.createWriteStream("./result.tar.gz");
const request = http.get("http://alpha.gnu.org/gnu/gzip/gzip-1.3.6.tar.gz", (response) => {
response.pipe(file);
});
How to download a file with nodeJS
This code uploads several different pictures
const url = 'https://i.pravatar.cc/225'
const https = require('https')
const fs = require('fs');
for(let i=0; i<10; i++)
https.get(url, resp => resp.pipe(fs.createWriteStream(`./test_${i}.jpeg`)));
Download a file without file ending nodejs
Here's an implementation using the got()
library for nodejs:
const got = require('got');
const url =
'https://preview.redd.it/04o5k2n06zd71.jpg?width=960&crop=smart&auto=webp&s=7baa25e7e1bde3436cb2a265e2fc8c6cb9a758ee';
got(url, { responseType: 'buffer' }).then(result => {
// result.body contains a Buffer object with the image in it
console.log(`content-type: ${result.headers['content-type']}`);
console.log(`isBuffer: ${Buffer.isBuffer(result.body)}`);
console.log(result.body);
}).catch(err => {
console.log(err);
});
You can run this code directly with nodejs (after installing the got()
library). When I run it, it generates this output:
content-type: image/jpeg
isBuffer: true
<Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e2 02 1c 49 43 43 5f 50 52 4f 46 49 4c 45 00 01 01 00 00 02 0c 6c 63 6d 73 02 10 00 00 ... 89335 more bytes>
Download a file from NodeJS Server using Express
Update
Express has a helper for this to make life easier.
app.get('/download', function(req, res){
const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
res.download(file); // Set disposition and send it.
});
Old Answer
As far as your browser is concerned, the file's name is just 'download', so you need to give it more info by using another HTTP header.
res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV');
You may also want to send a mime-type such as this:
res.setHeader('Content-type', 'video/quicktime');
If you want something more in-depth, here ya go.
var path = require('path');
var mime = require('mime');
var fs = require('fs');
app.get('/download', function(req, res){
var file = __dirname + '/upload-folder/dramaticpenguin.MOV';
var filename = path.basename(file);
var mimetype = mime.lookup(file);
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', mimetype);
var filestream = fs.createReadStream(file);
filestream.pipe(res);
});
You can set the header value to whatever you like. In this case, I am using a mime-type library - node-mime, to check what the mime-type of the file is.
Another important thing to note here is that I have changed your code to use a readStream. This is a much better way to do things because using any method with 'Sync' in the name is frowned upon because node is meant to be asynchronous.
Related Topics
How to Prevent the Keyboard from Popping Up on Mobile Devices
Charts.Js Graph Not Scaling to Canvas Size
Have a Div Move on Scroll Up and Down
Merge Array of Objects by Same Key-Value
Reload Table After Deleting an Item from It With React
How to Show an Alert After Reloading the Page in JavaScript
Executing Nodejs Script File in PHP Using Exec()
Detect If String Contains Any Spaces
How to Use Owl Carousel Vertically
Onclick Table Row With Onclick Button and Bootstrap Modal Inside
Generate Child Row Under a Parent Row in HTML Table
Filter Input Text to Enter Only Number and Not Even Decimal
How to Mock the JavaScript Window Object Using Jest
How to Create a Remember Me Function in Login Without Using Form in JavaScript or Jquery
How to Stop Parsefloat() from Stripping Zeroes to Right of Decimal
React-Native React-Navigation Undefined Is Not an Object (Evaluating 'S.Value.Startswith')
React Native How to Call Multiple Functions When Onpress Is Clicked