search

Home  >  Q&A  >  body text

node.js - When resquest.js pipe data stream downloads a file, how to automatically obtain the file suffix name and save it? In which step should I add it?

I want to get the suffix name of this link before fs.createWriteStream
Then pipe it to this data stream to save the file.

I have tried the Promise method, and then there is a complete response, which cannot be written to the data stream.
And I have also tried the fs.writeFile method, but the writing format is incorrect.

Note: There is no file extension in the URL

The following is the code

const fs = require('fs');
const Promise = require('bluebird');
const request = require('request');

let url = 'http://mmbiz.qpic.cn/mmbiz_jpg/D1Wza369eswnoapNaAdvtqygvMAnViaCLa8AMwwDZ4rebKrPvicxFf8zuibfialkPD3A7w8omWjicVm7GhFWcsibfGibw/0';
let file = fs.createWriteStream('file');

request
    .get(url)
    .on('response', function (response) {
        let type = response.headers['content-type']
        type = '.' + type.substring(type.lastIndexOf('/') + 1);
        console.log(type);
        // 在这里加是不可以的
    })
    .pipe(file)
    .on('end', function () {
        console.log('end')
    })
阿神阿神2806 days ago1374

reply all(1)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-16 13:30:40

    let type = '';
    request
        .get(url)
        .on('response', function (response) {
            type = response.headers['content-type']
            type = '.' + type.substring(type.lastIndexOf('/') + 1);
            console.log(type);
            // 在这里加是不可以的
        })
        .pipe(fs.createWriteStream('name'+type))
        .on('end', function () {
            console.log('end')
        })
    

    reply
    0
  • Cancelreply