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

后端 未结 28 1787
逝去的感伤
逝去的感伤 2020-11-22 03:37

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 giv

28条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 04:14

    download.js (i.e. /project/utils/download.js)

    const fs = require('fs');
    const request = require('request');
    
    const download = (uri, filename, callback) => {
        request.head(uri, (err, res, body) => {
            console.log('content-type:', res.headers['content-type']);
            console.log('content-length:', res.headers['content-length']);
    
            request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
        });
    };
    
    module.exports = { download };
    


    app.js

    ... 
    // part of imports
    const { download } = require('./utils/download');
    
    ...
    // add this function wherever
    download('https://imageurl.com', 'imagename.jpg', () => {
      console.log('done')
    });
    

提交回复
热议问题