AvianFlu / ncp

Asynchronous recursive file copying with Node.js.
MIT License
680 stars 103 forks source link

Callback is called before file is copied #143

Open Soulike opened 2 years ago

Soulike commented 2 years ago

The bug is caused by following code:

https://github.com/AvianFlu/ncp/blob/6820b0fbe3f7400fdb283c741ef88b6d8e2d4994/lib/ncp.js#L89-L109

As we can see, in line 108, cb() can be called before rmFile() and copyFile() finish their jobs. So if target file exists, cb() will be called before file is copied.

The test case below can reproduce the bug:

const destination = path.join(os.tmpdir(), 'bigFile');

ncp(someFile, destination, function (err)
{
    if (err)
    {
        return console.error(err);
    }
    ncp(someFile, destination, function (err)
    {
        if (err)
        {
            return console.error(err);
        }
        fs.readFileSync(destination);    // Error: ENOENT: no such file or directory, open '/tmp/bigFile'
    });
});