javascriptnode.jsfs-extra

JavaScript, Node.JS : Wait until copying a folder, then edit files in it (async, await)


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".


Solution

  • 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.