According to this question: What is the difference between __dirname and ./ in node.js? these 2 lines should be the same:
根据这个问题:node.js中__dirname和./有什么区别?这2行应该是相同的:
require(__dirname + '/folder/file.js');
require('./folder/file.js');
and I always used to use the second option. But now a project, I took over, the previous developer used require(__dirname + ...)
every time.
我总是习惯使用第二个选项。但是现在我接手了一个项目,以前的开发人员每次都使用require(__ dirname + ...)。
Personally I thinks it's harder to read and I'd like to change it, but maybe there is some advantage of this syntax I'm missing? Or is it the preferred version and I was doing it wrong all the time?
我个人认为它更难以阅读,我想改变它,但也许这种语法有一些优点我不见了?或者它是首选版本,我一直都在做错?
Just in case it matters, the libraries run sometimes on node.js with es6 enabled and sometimes on io.js (without additional flags).
为了防止重要,库有时在node.js上运行,启用es6,有时运行在io.js上(没有附加标志)。
1 个解决方案
#1
2
When using require()
there is no difference, using __dirname
is kind of redundant. The module loader will take care of the resolving the path correctly for you.
使用require()时没有区别,使用__dirname是多余的。模块加载器将负责为您正确解析路径。
When using one of the fs
methods like fs.readFile
there is a difference if your current working directory is not equal to __dirname
. If I want to read contents of a file called file.txt in the same directory as my script, I do:
当使用fs.readFile之类的fs方法时,如果当前工作目录不等于__dirname则会有所不同。如果我想在与脚本相同的目录中读取名为file.txt的文件的内容,我会这样做:
var Fs = require('fs');
var Path = require('path');
Fs.readFile(Path.join(__dirname, 'file.txt'), ...);
Then it doesn't matter what my cwd is when I start the node process that executes this code.
然后,当我启动执行此代码的节点进程时,我的cwd是什么并不重要。
#1
2
When using require()
there is no difference, using __dirname
is kind of redundant. The module loader will take care of the resolving the path correctly for you.
使用require()时没有区别,使用__dirname是多余的。模块加载器将负责为您正确解析路径。
When using one of the fs
methods like fs.readFile
there is a difference if your current working directory is not equal to __dirname
. If I want to read contents of a file called file.txt in the same directory as my script, I do:
当使用fs.readFile之类的fs方法时,如果当前工作目录不等于__dirname则会有所不同。如果我想在与脚本相同的目录中读取名为file.txt的文件的内容,我会这样做:
var Fs = require('fs');
var Path = require('path');
Fs.readFile(Path.join(__dirname, 'file.txt'), ...);
Then it doesn't matter what my cwd is when I start the node process that executes this code.
然后,当我启动执行此代码的节点进程时,我的cwd是什么并不重要。