Ashot Aleqsanyan
Ashot Aleqsanyan

Reputation: 4453

Can't parse the content of the file to the JSON becaouse of the comment in the first line

I am trying to get the file content as JSON format but I can't parse the JSON because of the first line

/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "module": "es2020",
    "lib": [
      "es2018",
      "dom"
    ]
  }
}

I am trying to get the file content by running this code in Node.JS


function initTSConfig() {
  const filePath = path.join(__dirname, 'tsconfig.json');
  readFile(filePath)
    .then(content => {
      // let config = JSON.parse(content);
      console.log(typeof content);
      console.log(`---> TS Config was changed successfully`);
    })
    .catch(e => {
      console.log(`---> TS Config was not changed because of ${e}`);
    })
}


function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf-8', (err, content) => {
      if (err) {
        console.warn(err);
        reject(err);
      }

      resolve(content);
    })
  })
}

Any help would be appreciated

Upvotes: 1

Views: 35

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370789

You could just slice off the first line before parsing.

readFile(filePath)
  .then((content) => {
    const json = content
      .split('\n')
      .slice(1)
      .join('\n');
    const parsedObj = JSON.parse(json);

Unless you're on an extremely outdated version of Node, I'd also suggest using fs.promises instead of a custom promisified readFile.

fs.promises.readFile(filePath, 'utf-8')
  .then((content) => {

Upvotes: 2

Related Questions