node.jskoa-router

async fs.promises.readfile breaks with koa-router@3.0.1 but works with koa-router@12.0.1


I have a Node.js 20.4.3 project which reads a list of files into an array and then generates a hash for each file. The code originally worked with koa-router@7.4.0, I upgraded to koa-router 13.0.1 and now it gives an exception when using readfile. Downgrading to koa-router@12.0.1 works fine.

The list of files is correctly processed from a configuration file and then parsed to an async hash generate function.

The calling function looks like

  let promiseArray = [];
  let filePaths = function() 
  {
    let tempFilePaths = [];
    for (let fileInfo of fileInfos) 
    {
      tempFilePaths.push(fileInfo.Path);
    }
    return tempFilePaths;
  }();

  for (let fileInfo of fileInfos) 
  {
    promiseArray.push(calculateFileSHA256Hash(fileInfo));
  }

  sha256HashArray = await Promise.all(promiseArray);

The Promise.all call returns an error.

ERROR: Unexpected ( at 35, expected END: https://git.new/pathToRegexpError

I have verified the filenames by sending them all to the logger. This is the async hashing function.

async function calculateFileSHA256Hash(fileInfo) 
{
  let urlFilePath = url.pathToFileURL(path.resolve(fileInfo.Path));
  try 
  {
    let fileName = path.basename(fileInfo.Path, path.extname(fileInfo.Path));
    let sha256Hash = createHash("sha256");

    let data = await fsPromises.readFile(urlFilePath);
    sha256Hash.update(data);
    let sha256HashSum = sha256Hash.digest("hex").toUpperCase();
    return {
      "file" : fileName,
      "hash" : sha256HashSum,
      "type" : fileInfo.Binary_Type
    };
  } 
  catch (err) 
  {
    logger.info(err);
  }
}

The error occurs when you have a regular expression in the get function of the koa-router.

const Router = require("@koa/router");

router.get(
  "/pkg/get-details/:labelSerialNumber(\\d-[0-9A-Za-z]{12})/",

Without regular expression works fine

const Router = require("@koa/router");

router.get(
  "/pkg/get-details/2-34570009000",

Solution

  • This appears to be a bug in koa-router which has now been replaced by @koa/router which doesn't have the issue.

    This link Wildcard route issue in Koa v13 details the issue.