2

im trying to download some files from a folder on nextcloud,using webdav. i want to iterate over folder and download all the files in it,here is my code:

let dir = "/foo"
let folder = await WebDav.getDirectoryContents("bar")

folder is returned as an array

for (let i = 0; i < folder.length; i++) {
    await WebDav.createReadStream(folder[0].filename).pipe(
    fs.createWriteStream(`${dir}/${folder[0].basename}`)
    );
  }
});

the files are created with correct names,but they have no content in them and their size are zero KBs

but when i put pipe outside of the for loop, it works fine and downloads the file.

ShayanJZ
  • 61
  • 4
  • 1
    You are trying to `await xxx.pipe()`, but `.pipe()` does not return a promise so that `await` will do nothing useful. Streams in general don't work directly with promises. streams don't come with built-in support for promises. You would have to wrap them yourself and hook up various event handlers to a promise. Or use `stream.pipeline()` and promisify that. The zero size is because your `for` loop is finishing before the files are written so you're probably trying to use the files before they've been written because the `await` does nothing useful. – jfriend00 Sep 19 '20 at 08:59

1 Answers1

1

Use this code , it worked for me

let fs = require('fs');
let { createClient } = require("webdav");
let start = async () => {
    let client = createClient(
            "https://*/on/demandware.servlet/webdav/Sites/Logs",
            {
                username: "*",
                password: "*"
            }
        );
    let directories = await client
    .getDirectoryContents("/");
    let files =  await directories;
    //console.log(files);
    
    for(let i =0; i< files.length ; i++) {
    let  fileName = files[i].filename;
    if(fileName.includes('.log')){
        let readStream =  client.createReadStream(fileName);
        // wait for 5 seconds, then pipe
        setTimeout(function() {

          let writeStream = readStream.pipe(fs.createWriteStream("C:/Users/*"+ fileName));

          writeStream.on('finish', function() {
            console.log('all done!');
          });

          writeStream.on('error', function(err) {
            console.error(err);
          });

        }, 5000);
    }
    }
}

 

start();
sonal
  • 41
  • 4