我需要使用相对于需要当前脚本的脚本的路径执行一些文件操作。
假设我们有以下内容 ~/somewhere/file2.js
const y = require('~/file1.js');
而在~/file1.js
我们有:
const x = require('./other/script.js'); //relative to ~/file1.js
我们像这样调用它:
cd ~/somedir
node ~/somewhere/file2.js
然后~/other/script.js
我们可以这样做:
console.log(__dirname); // -> ~/other
console.log(__filename); // -> ~/other/script.js
console.log(process.cwd()); // -> ~/somedir
console.log(process.argv[0]); // -> path/to/node
console.log(path.resolve('.')); // -> ~/somedir
console.log(process.argv[1]); // -> ~/somewhere/file2.js
这些都不是我需要的路径。
我如何从~other/script.js
确定需要我们的脚本的位置 - 即~/file1.js
换一种方式。~/somewhere/file2.js
需要~/file1.js
和~/file1.js
需要~/other/script.js
从内部~/other/script.js
我需要做相关的文件操作~/somewhere/file1.js
- 我怎样才能得到它的位置?
我实际上只需要file1.js
坐的目录,所以文件名或目录对我有用。
您可以使用module.parent.filename
inside of other/script.js
,也可以将其__dirname
作为参数传递给您的模块,例如require('other/script.js')(__dirname)
(假设您的模块导出一个函数)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句