如何获得基本目录,从需要在模块的NodeJS使用时不要../../../?
我的文件夹结构:
-base directory
--app.js
--models
---property.js
--routers
---api
----v1
-----properties.js
我的问题
在路由器/ API / V1 / properties.js,我该怎么办得到的基本目录,所以我可以停止这样做:
const Property = require('../../../models/property');
我想删除重复../../../
我目前的解决方案
在我的app.js,我添加一行:
global.__basedir = __dirname;
然后在路由器/ API / V1 / properties.js,
const path = require('path');
const Property = require(__basedir + '/models/property');
所以你怎么看?是否有陷阱,以这种方法吗?这是为了做到这一点,最好的方法是什么?
回答如下:使用app-root-path
模块(https://www.npmjs/package/app-root-path)。我已经在很多项目中使用,它派上用场。
const appRoot = require('app-root-path');
const myModule = require(appRoot + '/lib/my-module.js');
如何获得基本目录,从需要在模块的NodeJS使用时不要../../../?
我的文件夹结构:
-base directory
--app.js
--models
---property.js
--routers
---api
----v1
-----properties.js
我的问题
在路由器/ API / V1 / properties.js,我该怎么办得到的基本目录,所以我可以停止这样做:
const Property = require('../../../models/property');
我想删除重复../../../
我目前的解决方案
在我的app.js,我添加一行:
global.__basedir = __dirname;
然后在路由器/ API / V1 / properties.js,
const path = require('path');
const Property = require(__basedir + '/models/property');
所以你怎么看?是否有陷阱,以这种方法吗?这是为了做到这一点,最好的方法是什么?
回答如下:使用app-root-path
模块(https://www.npmjs/package/app-root-path)。我已经在很多项目中使用,它派上用场。
const appRoot = require('app-root-path');
const myModule = require(appRoot + '/lib/my-module.js');