Skip to content

Instantly share code, notes, and snippets.

@chowey
Created January 18, 2012 03:33
Show Gist options
  • Save chowey/1630693 to your computer and use it in GitHub Desktop.
Save chowey/1630693 to your computer and use it in GitHub Desktop.
Programmatically get a SyntaxError lineno from Node
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);
});
@chowey
Copy link
Author

chowey commented Jan 18, 2012

Since a SyntaxError does not return a lineNumber or fileName, we can extract these manually using stderr from child_process.

@chowey
Copy link
Author

chowey commented Jan 18, 2012

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