除了process.cwd()之外,是否有其他方法来获取当前项目根目录的路径名。Node是否实现了ruby的属性Rails.root之类的东西。我要找的是稳定可靠的东西。
当前回答
这将沿着目录树向下走,直到它包含一个node_modules目录,通常表示你的项目根目录:
const fs = require('fs')
const path = require('path')
function getProjectRoot(currentDir = __dirname.split(path.sep)) {
if (!currentDir.length) {
throw Error('Could not find project root.')
}
const nodeModulesPath = currentDir.concat(['node_modules']).join(path.sep)
if (fs.existsSync(nodeModulesPath) && !currentDir.includes('node_modules')) {
return currentDir.join(path.sep)
}
return this.getProjectRoot(currentDir.slice(0, -1))
}
它还确保返回路径中没有node_modules,因为这意味着它包含在嵌套包安装中。
其他回答
我用这个。
我的模块名为mymodule
var BASE_DIR = __dirname.replace(/^(.*\/mymodule)(.*)$/, '$1')
找到电子应用程序的根路径可能会很棘手。因为在不同的条件下,例如生产、开发和打包条件下,主进程和渲染器的根路径是不同的。
我写了一个npm包electronic -root-path来捕获电子应用程序的根路径。
$ npm install electron-root-path
or
$ yarn add electron-root-path
// Import ES6 way
import { rootPath } from 'electron-root-path';
// Import ES2015 way
const rootPath = require('electron-root-path').rootPath;
// e.g:
// read a file in the root
const location = path.join(rootPath, 'package.json');
const pkgInfo = fs.readFileSync(location, { encoding: 'utf8' });
简单:
require('path').resolve('./')
在使用express时,我发现一个有用的技巧是在设置任何其他路由之前将以下内容添加到app.js中
// set rootPath
app.use(function(req, res, next) {
req.rootPath = __dirname;
next();
});
app.use('/myroute', myRoute);
不需要使用全局变量,您可以将根目录的路径作为请求对象的属性。
如果你的app.js在你的项目的根目录中,这是有效的,默认情况下,它是。
我知道这已经太迟了。 但我们可以通过两个方法获取根URL
1号方法
var path = require('path');
path.dirname(require.main.filename);
2方法
var path = require('path');
path.dirname(process.mainModule.filename);
参考链接:—https://gist.github.com/geekiam/e2e3e0325abd9023d3a3
推荐文章
- ReferenceError: description没有定义NodeJs
- 将一个二进制的NodeJS Buffer转换为JavaScript的ArrayBuffer
- AngularJS只适用于单页应用程序吗?
- 如何在vue-cli项目中更改端口号
- 同步和异步编程(在node.js中)的区别是什么?
- 如何编辑通过npm安装的节点模块?
- “node_modules”文件夹应该包含在git存储库中吗
- 使用package.json在全局和本地安装依赖项
- this.libOptions.parse不是一个函数
- 对嵌套文件夹运行npm install的最好方法是什么?
- 节点Multer异常字段
- 很好的初学者教程socket.io?
- CALL_AND_RETRY_LAST分配失败-进程内存不足
- 在Ubuntu上安装Node.js
- 使用express.js代理