From d56b9498eaa1738f26aabd916456e6b6d6fcb933 Mon Sep 17 00:00:00 2001 From: William Oldham Date: Thu, 9 Jan 2025 21:06:21 +0000 Subject: [PATCH] fix: add __appRoot to fix bundler messing up __dirname for nested files --- src/app-root.ts | 4 ++++ src/services/npdi.ts | 3 ++- src/services/npts.ts | 5 +++-- 3 files changed, 9 insertions(+), 3 deletions(-) create mode 100644 src/app-root.ts diff --git a/src/app-root.ts b/src/app-root.ts new file mode 100644 index 0000000..410563a --- /dev/null +++ b/src/app-root.ts @@ -0,0 +1,4 @@ +// ! Do not move this file, it must be in the root of the project for __dirname to resolve correctly +// * Node.js does not have a built-in way to get the root directory of the project, so we need to set it manually +// * When using a bundler, __dirname will not work as expected in nested files so we need a consistent way to get the root directory +export const __appRoot = __dirname; diff --git a/src/services/npdi.ts b/src/services/npdi.ts index 5c23133..ee1c2e5 100644 --- a/src/services/npdi.ts +++ b/src/services/npdi.ts @@ -2,12 +2,13 @@ import path from 'node:path'; import express from 'express'; import subdomain from 'express-subdomain'; import { fileErrCallback } from '@/util'; +import { __appRoot } from '@/app-root'; const npdi = express.Router(); npdi.get('/p01/data/1/:titleHash/:dataID/:fileHash', (request, response) => { const { titleHash, fileHash } = request.params; - const contentPath = path.normalize(`${__dirname}/../../cdn/content/encrypted/${titleHash}/${fileHash}`); + const contentPath = path.normalize(`${__appRoot}../cdn/content/encrypted/${titleHash}/${fileHash}`); response.sendFile(contentPath, { headers: { diff --git a/src/services/npts.ts b/src/services/npts.ts index 7b5a044..48dbe63 100644 --- a/src/services/npts.ts +++ b/src/services/npts.ts @@ -2,12 +2,13 @@ import path from 'node:path'; import express from 'express'; import subdomain from 'express-subdomain'; import { fileErrCallback } from '@/util'; +import { __appRoot } from '@/app-root'; const npts = express.Router(); npts.get('/p01/tasksheet/:id/:hash/:fileName', (request, response) => { const { id, hash, fileName } = request.params; - const tasksheetPath = path.normalize(`${__dirname}/../../cdn/tasksheet/${id}/${hash}/${fileName}`); + const tasksheetPath = path.normalize(`${__appRoot}/../cdn/tasksheet/${id}/${hash}/${fileName}`); response.sendFile(tasksheetPath, { headers: { @@ -18,7 +19,7 @@ npts.get('/p01/tasksheet/:id/:hash/:fileName', (request, response) => { npts.get('/p01/tasksheet/:id/:hash/:subfolder/:fileName', (request, response) => { const { id, hash, subfolder, fileName } = request.params; - const tasksheetPath = path.normalize(`${__dirname}/../../cdn/tasksheet/${id}/${hash}/_subfolder/${subfolder}/${fileName}`); + const tasksheetPath = path.normalize(`${__appRoot}/../cdn/tasksheet/${id}/${hash}/_subfolder/${subfolder}/${fileName}`); response.sendFile(tasksheetPath, { headers: {