mscdex / node-ftp

An FTP client module for node.js
MIT License
1.13k stars 244 forks source link

Issues with the get function #172

Open theaaronmartin opened 7 years ago

theaaronmartin commented 7 years ago

I'm running into a weird issue where if the file path exists, the file downloads just fine, but if the path doesn't exist and I call mkdir, it downloads an empty file.

Logging stream shows it as both readable and writable at the beginning of the function and if the path exists, but if using mkdir, stream shows up as false for readable and writable.

Here's my code:

function ftpDownload (event, context, callback) {
    const c = new Client();
    const filePath = event.params.folderName + event.params.files;
    const destPath = event.params.destFolder + event.params.files;
    c.on('ready', function () {
        c.get(filePath, function (err, stream) {
            if (err) {
                return callback(err);
            }
            if (fs.existsSync(os.homedir() + '/' + event.params.destFolder)) {
                stream.once('close', function () {
                    c.end();
                });
                stream.pipe(fs.createWriteStream(os.homedir() + '/' + destPath));
                return callback(null, {status: 'completed'});
            } else {
                c.mkdir(event.params.destFolder, true, function (err) {
                    if (err) {
                        return callback(err);
                    }
                    console.log(stream);
                    stream.once('close', function () {
                        c.end();
                    });
                    stream.pipe(fs.createWriteStream(os.homedir() + '/' + destPath));
                    return callback(null, {status: 'completed'});
                });
            }
        });
    });
    // connect to {{url}} as {{username}} with {{password}}
    c.connect({
        host: event.params.host,
        user: event.params.username,
        password: event.params.password,
        port: event.params.port || '21',
        secure: false
    });
}