Using await with fs/promises function just exits code with no error

211 views Asked by At

I am at a loss as to why I cannot read files inside a directory. I have tried every implementation of fs (both standard and promise-based). With the code below, the main function is called, logs "Main function started..." and both oldDir and newDir, then exits with no error.

import { readdir, rename } from "fs/promises";
import * as path from "path";

const oldDir = path.join(process.cwd(), "../Old Backgrounds");
const newDir = process.cwd();

async function main() {
  console.log("Main function started...");
  console.log(oldDir);
  console.log(newDir);
  const oldFiles = await readdir(oldDir);
  const newFiles = await readdir(newDir);

  console.log(`File names to use: ${oldFiles}`);
  console.log(`Files to be renamed: ${newFiles}`);

  for (let i = 0; i < oldFiles.length; i++) {
    // Take new files and rename them to match oldFiles
    const currentName = newFiles[i];
    const newName = oldFiles[i];

    const currentPath = path.join(newDir, currentName);
    const renamePath = path.join(newDir, newName);

    await rename(currentPath, renamePath);
  }
}

main()
  .then(process.exit(0))
  .catch((e) => {
    console.error(e);
    process.exit(1);
  });

I am running this code on windows if that matters at all. When I use promises implementation with await readdir, the code exits with no error.

When I use a standard implementation with readdir and a callback function, it returns "undefined".

Both directories exist and have files in them.

1

There are 1 answers

0
Inconsequentia1 On

Solved per jonrsharpe's comment. The issue was not with my main function at all. I was passing process.exit(0) directly to then when it was looking for a callback function.

Revised the main function call to:

main()
  .then(() => process.exit(0))
  .catch((e) => {
    console.error(e);
    process.exit(1);
  });

And the issue disappeared.