Skip to content

Commit

Permalink
fix: add __appRoot to fix bundler messing up __dirname for nested files
Browse files Browse the repository at this point in the history
  • Loading branch information
binaryoverload committed Jan 9, 2025
1 parent fec123d commit d56b949
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 3 deletions.
4 changes: 4 additions & 0 deletions src/app-root.ts
Original file line number Diff line number Diff line change
@@ -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;
3 changes: 2 additions & 1 deletion src/services/npdi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
5 changes: 3 additions & 2 deletions src/services/npts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -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: {
Expand Down

0 comments on commit d56b949

Please sign in to comment.