0

I have the following code block where I'm passing from my .env, in a string that stores a json with the credentials for a google calendar.

const { google } = require('googleapis');
require('dotenv').config();
const CREDENTIALS = JSON.parse(process.env.CALENDAR_CREDENTIALS);
const CALENDAR_ID = process.env.CALENDAR_ID;

When I run this in Visual Studio Code in debug mode, the code works correctly without any issue. However, when I run it from the terminal using the prompt node google-calendar-testing.js I get the error:

(base) ENV:service ENV$ node google-calendar-testing.js 
undefined:1
undefined
^

SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at Object.<anonymous> (/Users/ENV/Invoice-Management-System/service/google-calendar-testing.js:4:26)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

How may I resolve this so that I can run this from the terminal? Any idea why this error might be happening when I run it from the terminal but not when I run it in debug mode using Node.js in Visual Studio Code?

For an additional check I added these lines of code to examine the undefined type, since the program isn't recognizing the string when I run from the terminal. Again the behaviour is weird. When I'm in debug mode the object type is a string. When I'm running from the terminal, the object type is undefined. Note sure why this is....

const credstype = typeof(process.env.CALENDAR_CREDENTIALS);
console.log(credstype)
const CREDENTIALS = JSON.parse(process.env.CALENDAR_CREDENTIALS);
ENV
  • 877
  • 2
  • 10
  • 32
  • Does this answer your question? [Uncaught SyntaxError: Unexpected token U in JSON at position 0 at JSON.parse () at Response.Body.json](https://stackoverflow.com/questions/42145287/uncaught-syntaxerror-unexpected-token-u-in-json-at-position-0-at-json-parse-a) – gowtham758550 Jun 22 '22 at 15:04
  • Not quite. The JSON parse is working when I'm in debug mode but when I run it from the terminal I get the error. So I'm not sure why I'm getting this different behaviour. I am passing in a valid JSON object so JSON parse shouldn't be throwing the error. – ENV Jun 23 '22 at 12:14

0 Answers0