Stack Exchange
mysql2 for Node js. SyntaxError: Unexpected token ':' when JSON.stringify is overridden
Without overriding JSON.stringify, the query works fine. When JSON.stringify is overridden, I get SyntaxError: Unexpected token ':'
This is the entire code. I run it with "node filename.js"
Why?
const mysql = require('mysql2');

const originalStringify = JSON.stringify;
/* without this override there is no error */
JSON.stringify = function (obj, replacer = null, space = 2) {
  return originalStringify(obj, replacer, space);
};

const connection = mysql.createConnection({
    host: 'localhost',
    port: 8889,
    user: 'root',
    password: 'root',
    database: 'flashcards'
});

try {
    connection.connect();
    connection.query('SELECT version()', function (error, results, fields) {
        if (error) throw error;
        console.log("result OK");
    });

} finally {
    connection.end();
}


When it works (by not overriding stringify and passing (results, null, 2) when stringify is called instead), the results look like this:
Query results: [
  {
    "version()": "5.7.39"
  }
]


I cannot reproduce this error in NodeJS v20.9.0, with simple objects and arrays of objects. How does results look like?

I added the results. It's not related to the results though. The query can be from any table. It's related to mysql2.

It is definitely related to the results, it does not happen with a basic object or array. What does results look like when you don't stringify it?

If you don't stringify the results then they look like "[object Object]".  That only works if you don't override the stringify function though. I can see that that's confusing, so I've updated the example to remove the direct call to stringify. The error still happens whether you call stringify or not. It happens because the stringify function is overridden.

Where is JSON.stringify() even being used? Does it only happen when you also use MySQL?

presumably it's being used in mysql2. The error only happens when mysql2 is used.

Try this:
const originalStringify = JSON.stringify.bind(JSON);

The original JSON.stringify() may be using this to refer to the JSON module, and it loses the reference when you call it through another variable.

the result is the same

It seems there was an internal dependency on the default behavior of JSON.stringify in the project that will be changed to avoid this issue in the future. (https://github.com/sidorares/node-mysql2/issues/2293)
