0

I am building a node.js program that copies a directory then edits the files in it. However, my code tries to edit the files before copying is done. I have tried adding await to the code, but could not solve the problem. The following is my code.

    const srcDir = `./old_dir`
    const destDir = `./new_dir`
    await fse.copy(srcDir, destDir, function (err) {
        if (err) throw err
    })

    // call the function that edits the files
    await create_page({info: queryparams})

I want to wait until copying the directory is complete, then call create_page. However, the following code calls create_page before copying the directory is done, which causes error of "no such file or directory".

trincot
  • 317,000
  • 35
  • 244
  • 286
ambb
  • 41
  • 6

2 Answers2

3

From the documentation of fs-extra:

All async methods will return a promise if the callback isn't passed.

Since you passed a callback to the copy method, the await will not "wait" for the async action to complete. So drop the callback argument:

const srcDir = `./old_dir`
const destDir = `./new_dir`
await fse.copy(srcDir, destDir);
// call the function that edits the files
await create_page({info: queryparams})

If you want anything else than re-throwing errors when they occur, then wrap the await code in a try...catch block.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • Realized that I had a fundamental problems. Thank you for the advise. Problem solved! I thought passing a callback to methods is necessary. – ambb Jul 22 '21 at 06:24
0

Adding an alternative to @trincot answer, you can also use copySync(src, dest[, options]) method which waits till the task is complete.

CyberDev
  • 228
  • 1
  • 7