Created
January 18, 2012 03:33
-
-
Save chowey/1630693 to your computer and use it in GitHub Desktop.
Programmatically get a SyntaxError lineno from Node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fn = '\n var o={a: "Hello";\n b:"World"};' | |
var child = require('child_process').spawn(process.execPath, ['-e', fn]); | |
child.stderr.setEncoding('utf8'); | |
child.stderr.on('data', function (data) { | |
var errLines = data.split('\n'); | |
var infoLine = errLines[1].split(':'); | |
var descLine = errLines[4]; | |
var filename = infoLine[0]; | |
var lineno = infoLine[1]; | |
console.log(descLine); | |
console.log('Filename: ' + filename); | |
console.log('Lineno: ' + lineno); | |
}); |
Much better would be to use vm.createScript
. If the third argument is true
, then we get the filename/lineno on stderr just like we do for a child_process. It has the advantage of running in the same process with lower overhead, which avoids async difficulties.
Unfortunately I don't know how to grab from stderr. The code that actually spits filename/lineno to stderr is in "node.cc", and is something like fprintf(stderr, ...)
. I can override stderr's write
method all I want and I won't get at the output from fprintf
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since a SyntaxError does not return a lineNumber or fileName, we can extract these manually using stderr from child_process.