TypeScript Cannot find name for 'JSON'
mwilki7 (653)

I'm attempting to get a simple NodeJS server programmed in TypeScript to send a client a json string but I get this error message:

app.get('/', function (req : any, res : any)
TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
    at Socket.<anonymous> (index.ts:17:47)
    at Socket.emit (events.js:198:13)
    at Socket.EventEmitter.emit (domain.js:448:20)
    at /home/runner/node_modules/socket.io/lib/socket.js:528:12
    at process._tickCallback (internal/process/next_tick.js:61:11)

Also, another error message appears under all lines that say 'JSON'

According to :
it says this issue is supposed to be fixed if JSON is the one causing the problem.

Anyone know what's wrong with the program?

You are viewing a single comment. View All
Answered by Klokat (41) [earned 5 cycles]
View Answer
Klokat (41)

@mwilki7 Alright this might be getting a bit complicated here and inefficient but try this:

In the server

var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data = JSON.stringify({
  'array': Array.from(imageData.data),
  'width': imageData.width
// Emit data

In the client

var obj = JSON.parse(data);
var colorData = new Uint8ClampedArray(obj.array);
var imageData = new ImageData(colorData, obj.width);
ctx.putImageData(imageData, 0, 0);

Sorry if there's a syntax error I didn't try running this.
The reason I'm calling Array.from(imageData.data) is because imageData.data is of type Uint8ClampedArray and JSON.stringify treats it like an object and not an array.
I'm also not sending ImageData as this will lose it's type when you serialize/stringify it. Instead I'm sending an object with the an array of pixels and the width of the image. Which on the client I use to construct in ImageData object with the pixel data and the width.

This whole back and forth with the data is probably not efficient but it should work. Hopefully.