Using node.js, I am trying to build an array of objects and write them to a file. For this, I use the built-in fs library.
After calling var file = fs.createWriteStream('arrayOfObjects.json'); and file.write('[') I run several asynchronous functions in order to ultimately add such objects:
file.write(JSON.stringify(objectToAppend) + ',\n')
I can determine when all objects stopped adding, and this is where I run file.write(']') and file.end() . My problem is that adding the last comma to the end of the last object causes the JSON to be invalid.
It is very difficult to determine where and when the last object is created due to the asynchronous nature of the script, so I was wondering if there was a way to remove or remove characters from the file stream. If so, I could do this before adding the last character ']' .
I could do it manually, but I was hoping to transfer this to another application. The only solution I thought of is to use the fs.truncate() function, however this does not work for file streams, and neither file.length nor file.length() will give me the length of the content because it is not a string, therefore Itβs difficult to determine how and where to trim the file.
Now I just added '{}]' to the end of the array to make it valid JSON, but this empty object may cause some problems later.
Also note: the array of objects that I write in this stream is VERY large, so I would prefer not to stop the stream and not open the file .
source share