| 1 |
# syntax-error |
| 2 |
|
| 3 |
Detect and report syntax errors in source code strings. |
| 4 |
|
| 5 |
[](http://travis-ci.org/substack/node-syntax-error) |
| 6 |
|
| 7 |
When you type `node src.js` you get a friendly error report about exactly where |
| 8 |
the syntax error is. This module lets you check for syntax errors and report |
| 9 |
them in a similarly friendly format that wrapping a try/catch around |
| 10 |
`Function()` or `vm.runInNewContext()` doesn't get you. |
| 11 |
|
| 12 |
# example |
| 13 |
|
| 14 |
``` js |
| 15 |
var fs = require('fs'); |
| 16 |
var check = require('syntax-error'); |
| 17 |
|
| 18 |
var file = __dirname + '/src.js'; |
| 19 |
var src = fs.readFileSync(file); |
| 20 |
|
| 21 |
var err = check(src, file); |
| 22 |
if (err) { |
| 23 |
console.error('ERROR DETECTED' + Array(62).join('!')); |
| 24 |
console.error(err); |
| 25 |
console.error(Array(76).join('-')); |
| 26 |
} |
| 27 |
``` |
| 28 |
|
| 29 |
--- |
| 30 |
|
| 31 |
``` |
| 32 |
$ node check.js |
| 33 |
ERROR DETECTED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! |
| 34 |
|
| 35 |
/home/substack/projects/node-syntax-error/example/src.js:5 |
| 36 |
if (Array.isArray(x) res.push.apply(res, x); |
| 37 |
^ |
| 38 |
ParseError: Unexpected identifier |
| 39 |
--------------------------------------------------------------------------- |
| 40 |
``` |
| 41 |
|
| 42 |
# methods |
| 43 |
|
| 44 |
``` js |
| 45 |
var check = require('syntax-error') |
| 46 |
``` |
| 47 |
|
| 48 |
## var err = check(src, file, opts={}) |
| 49 |
|
| 50 |
Check the source code string `src` for syntax errors. |
| 51 |
Optionally you can specify a filename `file` that will show up in the output. |
| 52 |
|
| 53 |
If `src` has a syntax error, return an error object `err` that can be printed or |
| 54 |
stringified. |
| 55 |
|
| 56 |
If there are no syntax errors in `src`, return `undefined`. |
| 57 |
|
| 58 |
Options will be passed through to [acorn-node](https://github.com/browserify/acorn-node). |
| 59 |
acorn-node defaults to options that match the most recent Node versions. |
| 60 |
|
| 61 |
## err.toString() |
| 62 |
|
| 63 |
Return the long string description with a source snippet and a `^` under |
| 64 |
pointing exactly where the error was detected. |
| 65 |
|
| 66 |
# attributes |
| 67 |
|
| 68 |
## err.message |
| 69 |
|
| 70 |
short string description of the error type |
| 71 |
|
| 72 |
## err.line |
| 73 |
|
| 74 |
line number of the error in the original source (indexing starts at 1) |
| 75 |
|
| 76 |
## err.column |
| 77 |
|
| 78 |
column number of the error in the original source (indexing starts at 1) |
| 79 |
|
| 80 |
# install |
| 81 |
|
| 82 |
With [npm](http://npmjs.org) do: |
| 83 |
|
| 84 |
``` |
| 85 |
npm install syntax-error |
| 86 |
``` |
| 87 |
|
| 88 |
# license |
| 89 |
|
| 90 |
MIT |