Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to configure the __dirname to point to project directory in node?

I am adding a sequelize to my node project, it adds the following index.js file as a part of the setup, but when I run the project the __dirname resolves to my C: directory instead of the project root folder C:\workspace\myapp. How do I configure it so that it resolves to my project root directory?

index.js file

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs.readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    const model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

package.json

{
  "name": "my-app-model",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "format": "prettier --write \"src/**/*.{js,jsx,ts,tsx}\"",
    "start": "next start",
    "type-check": "tsc"
  },
  "dependencies": {
    "@material-ui/core": "^4.8.3",
    "@material-ui/lab": "4.0.0-alpha.39",
    "mysql": "^2.18.1",
    "mysql2": "^2.1.0",
    "next": "9.1.7",
    "prettier": "^1.19.1",
    "react": "16.12.0",
    "react-dom": "16.12.0",
    "sequelize": "^5.21.7",
    "sequelize-cli": "^5.5.1"
  },
  "devDependencies": {
    "@types/node": "^13.1.6",
    "@types/react": "^16.9.17",
    "@types/react-dom": "^16.9.4",
    "typescript": "^3.7.4"
  }
}

like image 285
arve Avatar asked Sep 03 '25 06:09

arve


1 Answers

I believe the immediate solution is to replace __dirname with something like:

const modelsDir = path.resolve(process.cwd(), 'path/to/models')
fs.readdirSync(modelsDir)
  .filter(....

Making __dirname work the way we expect is a known issue on next.js:

I expected __dirname to be the absolute path of the file in which getStaticProps is being executed, but instead it is incorrectly resolving as /.

Here's the issue rephrased as a feature request: https://github.com/vercel/next.js/issues/8251

A little background on how this manifested for me in case this helps someone find this solution:

I'm using a mac, but I was having a very similar problem. I am setting up a next.js app with sequelize. After I ran the sequelize-cli to generate the models/index.js that you quote above, I first saw this error:

Error: Cannot find module '/Applications'
Require stack:
- /Users/username/src/mariner-next/node_modules/sequelize/lib/sequelize.js
- /Users/username/src/mariner-next/node_modules/sequelize/index.js
- /Users/username/src/mariner-next/.next/server/static/development/pages/api/graphql.js
- /Users/username/src/mariner-next/node_modules/next/dist/next-server/server/next-server.js
- /Users/username/src/mariner-next/node_modules/next/dist/server/next.js
- /Users/username/src/mariner-next/node_modules/next/dist/server/lib/start-server.js
- /Users/username/src/mariner-next/node_modules/next/dist/cli/next-dev.js
- /Users/username/src/mariner-next/node_modules/next/dist/bin/next
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:981:15)
    at Function.Module._load (internal/modules/cjs/loader.js:863:27)
    at Module.require (internal/modules/cjs/loader.js:1043:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Sequelize.import (/Users/username/src/mariner-next/node_modules/sequelize/lib/sequelize.js:481:62)
    at eval (webpack-internal:///./tnr/lib/models/index.js:60:36)
    at Array.forEach (<anonymous>)
    at Module.eval (webpack-internal:///./tnr/lib/models/index.js:58:4)

After some head scratching, I realized that __dirname is set to "/" and so fs.readdrSync(__dirname) is returning a list of my root directory.

like image 113
Matt Raibert Avatar answered Sep 04 '25 19:09

Matt Raibert