skip to Main Content

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"
  }
]

2

Answers


  1. Chosen as BEST ANSWER

    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)


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search