Implement a factory registry for parsers
Implement a factory registry for parsers in JavaScript: choose a parser by file extension and add new ones without edits. Node.js 24.
A function that picks a parser with an if chain must change for every new format. A registry maps extensions to factories, and a new format is one register call.
const parsers = new Map();
const registerParser = (ext, create) => parsers.set(ext, create);
function parse(filename, text) {
const ext = filename.slice(filename.lastIndexOf('.') + 1);
const create = parsers.get(ext);
if (!create) throw new Error(`no parser for .${ext}`);
return create().parse(text);
}
registerParser('json', () => ({ parse: JSON.parse }));
registerParser('csv', () => ({
parse: (text) => text.split('\n').map((line) => line.split(',')),
}));
console.log(parse('data.json', '{"a":1}'));
console.log(parse('rows.csv', 'a,b\n1,2'));
try {
parse('notes.xml', '<a/>');
} catch (error) {
console.log(error.message);
}{ a: 1 }
[ [ 'a', 'b' ], [ '1', '2' ] ]
no parser for .xmlThe factory returns a fresh parser per call, so a parser with state does not leak between files. A plugin can call registerParser('yaml', ...) and parse needs no change.
A filename without a dot gives lastIndexOf of -1, so the whole name is treated as the extension and fails with a clear message. For anything beyond two or three formats, validate the registry at startup.