node中路径位置

当文件路径是:/a/b/c/index.js

jsvar path = require('path');

console.log('require.resolve => ' + require.resolve('./index.js'));
console.log('path.resolve(./index.js) => ' + path.resolve('./index.js'));
console.log('__dirname => ' + __dirname);

执行cd /a/b/c/ && node ./index.js输出的结果是:

require.resolve => /a/b/c/index.js
path.resolve(./index.js) => /a/b/c/index.js
__dirname => /a/b/c

执行cd / && node /a/b/c/index.js输出的结果是:

require.resolve => /a/b/c/index.js
path.resolve(./index.js) => /index.js
__dirname => /a/b/c

结论

ps:之前一直用path.resolve(__dirname, './index.js')来查找当前文件目录下的index.js,现在可以直接使用require.resolve('./index.js')来引用了,么么哒~

require.resolve是用来查找完整模块名称id的,用时得谨慎