Read json file ignoring custom comments

The perfect package for this problem is https://www.npmjs.com/package/hjson

hjsonText input:


{
  # hash style comments
  # (because it's just one character)

  // line style comments
  // (because it's like C/JavaScript/...)

  /* block style comments because
     it allows you to comment out a block */

  # Everything you do in comments,
  # stays in comments ;-}
}

Usage:

var Hjson = require('hjson');

var obj = Hjson.parse(hjsonText);
var text2 = Hjson.stringify(obj);

The package you are looking for is called strip-json-comments - https://github.com/sindresorhus/strip-json-comments

const json = '{/*rainbows*/"unicorn":"cake"}';

JSON.parse(stripJsonComments(json)); //=> {unicorn: 'cake'}

You can use your own RegExp pretty easily to match the comments beginning with a #

const matchHashComment = new RegExp(/(#.*)/, 'gi');
const fs = require('fs');

fs.readFile('./file.json', (err, data) => {
    // replaces all hash comments & trim the resulting string
    let json = data.toString('utf8').replace(matchHashComment, '').trim();  
    json = JSON.parse(json);
    console.log(json);
});