gcode-parser
raw JSON → 2.2.0 verified Sat May 09 auth: no javascript
G-code parser for Node.js, current stable version 2.2.0. Maintained as part of the cncjs ecosystem. Provides synchronous and asynchronous parsing of G-code strings, lines, files, and streams. Key differentiators: supports line modes (original, stripped, compact) and flatten option for word representation. Used widely in CNC toolpath generation and visualization.
Common errors
error TypeError: parser.parseFile is not a function ↓
cause Using ES module import syntax with require or missing installation.
fix
Use const parser = require('gcode-parser'); and run in Node.js CJS environment.
error TypeError: Cannot read property '0' of undefined ↓
cause Assuming words are always present in result, but empty lines return { words: [] }.
fix
Check for empty array before accessing elements: if (result.words.length > 0) { ... }
error TypeError: callback is not a function ↓
cause Calling parseFile without a second argument (callback) or passing a non-function.
fix
Always provide a callback: parser.parseFile('file.nc', (err, result) => { ... });
Warnings
gotcha parseFile and parseString callbacks accept (err, results) but also return an EventEmitter. Not handling both can lead to missed events. ↓
fix Use callback for results, and attach listeners for 'data' or 'end' if needed.
gotcha parseLine with options object: lineMode and flatten should be passed as second argument. Omitting options uses defaults. ↓
fix Correct: parser.parseLine('G0 X0', { flatten: true }); Incorrect: parser.parseLine('G0 X0', true);
gotcha Result words are arrays of [letter, number] in non-flatten mode. Forgetting this can cause type errors. ↓
fix Access word[0] for letter and word[1] for value, or use flatten: true to get strings like 'G0'.
Install
npm install gcode-parser yarn add gcode-parser pnpm add gcode-parser Imports
- default wrong
import parser from 'gcode-parser';correctconst parser = require('gcode-parser'); - parseLine wrong
parseLine('G0 X0 Y0');correctparser.parseLine('G0 X0 Y0'); - parseFile wrong
parser.parseFile('file.nc');correctparser.parseFile('file.nc', callback); - parseStringSync
const results = parser.parseStringSync('G0 X0');
Quickstart
const fs = require('fs');
const parser = require('gcode-parser');
// Parse a single line
console.log(parser.parseLine('G0 X0 Y0'));
// => { line: 'G0 X0 Y0', words: [ [ 'G', 0 ], [ 'X', 0 ], [ 'Y', 0 ] ] }
// Parse a file asynchronously
parser.parseFile('example.nc', (err, results) => {
if (err) throw err;
console.log(results);
});
// Parse a string synchronously
const str = fs.readFileSync('example.nc', 'utf8');
const results = parser.parseStringSync(str);
console.log(results);