mirror of
https://github.com/ThatGuySam/doesitarm.git
synced 2026-05-15 06:35:20 -07:00
Add streamToJson helper
This commit is contained in:
parent
9f29e2002d
commit
ea40288bea
1 changed files with 33 additions and 0 deletions
33
helpers/json.js
Normal file
33
helpers/json.js
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
import fs from 'fs'
|
||||||
|
|
||||||
|
// Write JSON to file via stream
|
||||||
|
// so that we can handle large JSON files
|
||||||
|
// that would not normal fit into memory
|
||||||
|
// or V8 string size limits
|
||||||
|
export function streamToJson ( dataArray, filePath ) {
|
||||||
|
return new Promise( resolve => {
|
||||||
|
const output = fs.createWriteStream( filePath, 'utf8' )
|
||||||
|
|
||||||
|
// When the stream is finished
|
||||||
|
output.on( 'finish', () => {
|
||||||
|
resolve( output )
|
||||||
|
})
|
||||||
|
|
||||||
|
// Write opening array bracket
|
||||||
|
output.write( '[' )
|
||||||
|
|
||||||
|
// Write each item in the array
|
||||||
|
for ( const item of dataArray ) {
|
||||||
|
output.write( JSON.stringify( item ) + ',' )
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write closing array bracket
|
||||||
|
output.write( ']' )
|
||||||
|
|
||||||
|
// Close the stream
|
||||||
|
output.end()
|
||||||
|
|
||||||
|
// Return the stream
|
||||||
|
return output
|
||||||
|
})
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue