最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

如何获得基本目录,从需要在模块的NodeJS使用时不要......?

IT培训 admin 10浏览 0评论

如何获得基本目录,从需要在模块的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');
发布评论

评论列表 (0)

  1. 暂无评论