NodeJS中模块的应用基本路径 [英] App base path from a module in NodeJS

查看:180
本文介绍了NodeJS中模块的应用基本路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在NodeJS中构建一个Web应用程序,并在单独的模块中实现我的API路由.在我的一条路线中,我正在做一些文件操作,我需要知道基本应用程序的路径.如果我使用__dirname,它会为我提供存放我的模块的目录.

I'm building a web app in NodeJS, and I'm implementing my API routes in separate modules. In one of my routes I'm doing some file manipulation and I need to know the base app path. if I use __dirname it gives me the directory that houses my module of course.

我目前正在使用它来获取基本应用程序路径(假设我知道从基本路径到模块的相对路径):

I'm currently using this to get the base app path (given that I know the relative path to the module from base path):

path.join(__dirname, "../../", myfilename)

有没有比使用../../更好的方法?我在Windows下运行Node,所以没有process.env.PWD,而且我也不想成为特定于平台的东西.

Is there a better way than using ../../? I'm running Node under Windows so there is no process.env.PWD and I don't want to be platform specific anyway.

推荐答案

使用> 是最可靠的.它将始终为您提供正确的目录.您不必担心Windows环境中的../../,因为 path.join() 将照顾.

The approach of using __dirname is the most reliable one. It will always give you correct directory. You do not have to worry about ../../ in Windows environment as path.join() will take care of that.

不过,还有另一种解决方案.您可以使用 process.cwd() 返回该进程的当前工作目录.如果您从基本应用程序目录执行节点应用程序,则该命令可以正常工作.但是,如果从不同的目录(例如,其父目录(例如node yourapp\index.js)然后__dirname机制)运行"来执行节点应用程序,则效果会更好.

There is an alternative solution though. You can use process.cwd() which returns the current working directory of the process. That command works fine if you execute your node application from the base application directory. However, if you execute your node application from different directory, say, its parent directory (e.g. node yourapp\index.js) then __dirname mechanism will work much better.

我希望这会有所帮助.

这篇关于NodeJS中模块的应用基本路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆