REPL模式与运行.js的区别(比如说__dirname)的问题
发布于 1年前 作者 ceclinux 528 次浏览

我一直以为这两种是一样的,直到发现

 cecil[@cecil-Aspire-4750](/user/cecil-Aspire-4750)  ~/Dropbox/node  node
 > console.log(__dirname)
 ReferenceError: __dirname is not defined
at repl:1:14
at REPLServer.self.eval (repl.js:110:21)
at Interface.<anonymous> (repl.js:239:12)
at Interface.EventEmitter.emit (events.js:95:17)
at Interface._onLine (readline.js:202:10)
at Interface._line (readline.js:531:8)
at Interface._ttyWrite (readline.js:760:14)
at ReadStream.onkeypress (readline.js:99:10)
at ReadStream.EventEmitter.emit (events.js:98:17)
at emitKey (readline.js:1095:12)

而这样却可以

 ✘ cecil[@cecil-Aspire-4750](/user/cecil-Aspire-4750)  ~/Dropbox/node  echo "console.log(__dirname)" > test.js 
 cecil[@cecil-Aspire-4750](/user/cecil-Aspire-4750)  ~/Dropbox/node  node test.js                            
 /home/cecil/Dropbox/node

我想知道为什么会这样,这两种模式有什么本质上的不同吗? 可能有点钻牛角尖了

2 回复

The name of the directory that the currently executing script resides in.

from http://nodejs.org/api/globals.html#globals_dirname

首先你得是个 script

REPL其实也可以得到:

PS C:\mongodb\bin> node
> process.cwd()
'C:\\mongodb\\bin'

这个并没有如此简单吧,我在学习这篇的时候 mongoose教程 在REPL下会抛出

> personEntity.speak();
TypeError: Object { name: 'Krouky', _id: 52f48d9dba3964b539a9acff } has no method 'speak'
    at repl:1:14
    at REPLServer.self.eval (repl.js:110:21)
    at repl.js:249:20
    at REPLServer.self.eval (repl.js:122:7)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)
    at ReadStream.onkeypress (readline.js:99:10)
回到顶部