乐趣区

关于node.js:dirname-filename-pathresolve-pathjoin-processcwd

MasOs 零碎,在终端中, /Users/a1234/Desktop/ 目录下,执行命令 node script/demo.js


\# __dirname – 返回以后模块的目录名

console.log(__dirname); 
>>> /Users/a1234/Desktop/script

输入后果:以后文件所在目录的绝对路径

\# __filename – 返回以后模块文件的文件名,蕴含绝对路径

console.log(__filename); 
>>> /Users/a1234/Desktop/script/demo.js

输入后果:以后文件的绝对路径

\# path.resolve() – 解析门路,返回绝对路径

console.log(path.resolve()); 
>>> /Users/a1234/Desktop

console.log(path.resolve('./demo.js')); 
>>> /Users/a1234/Desktop/demo.js

console.log(path.resolve(__dirname, './demo.js')); 
>>> /Users/a1234/Desktop/script/demo.js

输入后果:Node.js 过程当前工作的目录 + 传入参数(相对路径)的组合

\# path.join() – 拼接门路,返回拼接后的门路

console.log(path.join()); 
>>> .

console.log(path.join('./demo.js')); 
>>> demo.js

console.log(path.join(__dirname, './demo.js')); 
>>> /Users/a1234/Desktop/script/demo.js

输入后果:传入参数(相对路径)的组合

\# process.cwd() – 返回 Node.js 过程当前工作的目录

console.log(process.cwd()); 
>>> /Users/a1234/Desktop

输入后果:Node.js 过程当前工作的目录


! 总结

优先应用 path.resolve;能够适配绝大多数场景;

退出移动版