简体   繁体   中英

how to donwload and save several files with nodejs?

I need make to program in nodejs which take lists files of another website and save in my machine.

for example:

 function saveLocalFiles(files) { for (var i in files) { var file = fs.createWriteStream(path.join(__dirname, "media/" + files[i].FILE)); console.log(URL + files[i].FILE); http.get(URL + files[i].FILE, function (response) { response.pipe(file); file.on('finish', function () { file.close(() => { console.log("ends ->" + files[i].FILE); }); }); }) } } 

when I execute it my code does not work with several files. Also, I can't know when it ends to download the files. Can somebody help me?.

Thank you.

use Promises and try to split your code in two functions :

function saveLocalFiles(files) {
    Promise
        .all(files.map(file => saveLocalFile((URL, file.FILE))))
        .then((files) => {
            console.log(files);
        })
 }

function saveLocalFile(URL, FILE) {
    return new Promise((resolve) => {
        var file = fs.createWriteStream(path.join(__dirname, "media/" + FILE));
        console.log(URL + FILE);
        http.get(URL + FILE, function (response) {
            response.pipe(file);
            file.on('finish', function () {
                file.close(() => {
                    console.log("ends ->" + FILE);
                    resolve(FILE);
                });
            });
        })
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM