1.require.main.filename

1
2
var path = require("path");
var appDir = path.dirname(require.main.filename);

2.global.X

1
2
3
4
5
6
// index.js
var path = require("path");
global.appRoot = path.resolve(__dirname);

// lib/moduleA/component1.js
require(appRoot + "/lib/moduleB/component2.js");

3.process.cwd()

1
2
3
4
5
6
7
8
$ cd /home/demo/
$ mkdir subdir
$ echo "console.log(process.cwd());" > subdir/demo.js
$ node subdir/demo.js
/home/demo
$ cd subdir
$ node demo.js
/home/demo/subdir

4.app-root-path

使用该包 https://github.com/inxilpro/node-app-root-path