在Node.js调试时如何查看变量?

3
Node.js调试器会隐藏大部分字符串变量,用...代替打印输出,比如以下代码(其中有一个名为source的变量):
$ node debug 127.0.0.1:9101
debug> 
debug> exec('source')
'<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" class="DW dw-pri js no... (length: 6408)'
debug>
debug> repl
Press Ctrl + C to leave debug repl
> source
'<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" class="DW dw-pri js no... (length: 6408)'

如您所见,它用...替换了大部分字符串。我已经谷歌了一会儿,在控制台中输入了help。最终在这里发布 - 如何查看字符串的完整内容?console.log(source)没有任何作用。
编辑:现在我注意到,在Selenium的终端窗口中,console.log确实打印变量,这也许是我应该预期的。不确定是否应该使用console.log并切换到Selenium终端窗口。
更新:
repl之外仅输入source无效。
debug> source
ReferenceError: source is not defined
    at repl:1:1
    at ContextifyScript.Script.runInContext (vm.js:32:29)
    at Object.runInContext (vm.js:87:6)
    at Interface.controlEval (_debugger.js:971:21)
    at REPLServer.eval (_debugger.js:745:41)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.onLine (repl.js:536:10)
    at emitOne (events.js:96:13)
    at REPLServer.emit (events.js:191:7)

当在repl中时,变量会被截断,如上面的代码片段所示。

print(source)print('source')

debug> print('source')
ReferenceError: print is not defined
    at repl:1:1
    at ContextifyScript.Script.runInContext (vm.js:32:29)
    at Object.runInContext (vm.js:87:6)
    at Interface.controlEval (_debugger.js:971:21)
    at REPLServer.eval (_debugger.js:745:41)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.onLine (repl.js:536:10)
    at emitOne (events.js:96:13)
    at REPLServer.emit (events.js:191:7)
debug> repl
Press Ctrl + C to leave debug repl
> print(source)
ReferenceError: print is not defined

在调试器中可供选择的命令并不多:

debug> help
Commands: run (r), cont (c), next (n), step (s),
out (o), backtrace (bt), setBreakpoint (sb), clearBreakpoint (cb),
watch, unwatch, watchers, repl, exec, restart, kill, list, scripts,
breakOnException, breakpoints, version

1
你尝试过在调试命令行中只输入变量名称而不使用 console.log() 吗? - Soviut
print 代替 exec 怎么样? - OmG
嗨@Soviut,我测试了输入“source”。然后调试器找不到“source”,因为“source”变量仅在Node.js调试进程中可用,而不在调试器本身中。 - KajMagnus
@torazaburo 我正在使用webdriver.io,它会派生一个子进程来运行Selenium端到端测试。然而,DevTools连接到了错误的进程——主Node.js进程。命令行node debug 127.0.0.1:9101连接到了正确的进程。但是我不知道如何告诉Chrome连接到正确的进程——URL似乎包含了一些神奇/秘密的令牌:chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9100/c439ac7f-8022-4b5f-b971-dc50fd73335c——这是错误的端口:9100而不是9101。将其更改为9101也无效。 - KajMagnus
如果您选择“远程设备”,它可能会显示您可以连接到的进程,而无需担心奇怪的URL。 - user663031
显示剩余3条评论
1个回答

2

watch("your_var_name")将在每个断点处打印您观察的变量/表达式的值(您必须用引号括起变量/表达式名称)。

虽然在命令行上似乎没有更接近的东西,但坦白地说,只需编写

console.log(thing I want to log); debugger;

对我来说更容易一些。

注:watch和console.log都是调试JavaScript代码时常用的工具。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接