0

I am using request module in nodejs to download a file(only image file) using this,

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png')),

or say

request(url).pipe(fs.createWriteStream(filename)),

but I have only url available and I have required to save the file with its actual name, So I have required to found filename from the given url,

please suggest me method which donot extracted last part of url

Thanks in advance...

Rajit Garg
  • 529
  • 9
  • 22
  • possible duplicate of [node.js Writing image to local server](http://stackoverflow.com/questions/5294470/node-js-writing-image-to-local-server) – Michael Oct 10 '14 at 13:53

1 Answers1

0

A simple solution might be:

var path = require('path');
var fs = require('fs');

// ...

var filename = path.basename(url);

request(url).pipe(fs.createWriteStream(filename));
mscdex
  • 104,356
  • 15
  • 192
  • 153
  • no mscdex, I have not required this, I know this extract the last part of url and my URL is somewhat different, consist of file key and Token like http://beta.business.applane.com/rest/file/download?token=5437bdb1811dfb0f03ec49a3&filekey=541bc4c909e41ce549567c07, which gives below file name download?token=5437bdb1811dfb0f03ec49a3&filekey=541bc4c909e41ce549567c07, but actually its filename is photo.jpg, is there any way to get this... – Rajit Garg Oct 11 '14 at 04:20
  • Well, in that case, check your `Content-Disposition` header value. If it has a `filename` parameter in it, then you need to extract that. FWIW [this function](https://github.com/mscdex/busboy/blob/3a24ac52aa02433f0f44b2a5954fd4e3e3ee3079/lib/utils.js#L7-L91) is what the `busboy` module uses to parse those kinds of header values. – mscdex Oct 11 '14 at 04:47
  • I am not getting Content-Disposition in response.headers – Rajit Garg Oct 11 '14 at 05:40
  • Then where is `photo.jpg` coming from in the response? – mscdex Oct 11 '14 at 05:43