jonschlinkert / copy

Copy files using glob patterns. Sync, async, promise or streams. (node.js utility)
MIT License
94 stars 125 forks source link

Unexpected callback behavior when using globs #22

Open gmhenderson opened 7 years ago

gmhenderson commented 7 years ago

The callback isn't behaving as I expect when using glob file patterns.

This works as you might expect:

copy('src/api/public/index.php', 'dist', function (err, file) {})
// -> index.php is copied to dist/src/api/public/index.php

So, naturally, if I want to perform some action on index.php after its copied, I do something like:

copy('src/api/public/index.php', 'dist', function (err, file) {
  console.log(fs.statSync('dist/src/api/public/index.php'))
})
// -> File is found, all is well

Now consider:

copy('src/api/public/*', 'dist', function (err, file) {})
// -> index.php is copied to dist/index.php

But then this doesn't work:

copy('src/api/public/*', 'dist', function (err, file) {
  console.log(fs.statSync('dist/index.php'))
})

Output:

Error: ENOENT: no such file or directory, stat 'dist/index.php'

Why can't fs.statSync find the file when using the *?

jonschlinkert commented 7 years ago

Hmm, yeah that's not right. I'll look into it. thanks

KristofferBerge commented 7 years ago

Same problem here. I'm able to get it working by setting a timeout between copying and writing to the copied folders for now. Probably not the best workaround though.

    function copyFilesAsync(path, destination) {
        return new Promise((resolve, reject) => {
            copy(path, destination, resolve);
        })
    }
    function timeout(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
    await copyFilesAsync('src/**/*', 'temp/src');
    await timeout(100); // Throws error without awaited timeout
    fs.writeFile("./temp/myfile.json", JSON.stringify(content, null, 4), function () {
        resolve();
    });