Last active
May 1, 2019 01:51
-
-
Save chadbr/b21ac6ee49a8955fb062267e401a2aea to your computer and use it in GitHub Desktop.
Write a file with Typescript 3.x and node 10.x fs/promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { promises as fs } from 'fs'; | |
import { EOL } from 'os'; | |
export class SomeClass { | |
async asyncFileWriteJSON<T>(listOfObjects: Array<T>, filename: string): Promise<void> { | |
try { | |
if (listOfObjects && listOfObjects.length > 0) { | |
const file = filename; | |
let fd = await fs.open(file, 'w'); | |
await fd.appendFile('['); | |
for (let index = 0; index < listOfObjects.length; index++) { | |
if (index === listOfObjects.length - 1) { | |
await fd.appendFile(`${JSON.stringify(listOfObjects[index])}${EOL}`); | |
} else { | |
await fd.appendFile(`${JSON.stringify(listOfObjects[index])},${EOL}`); | |
} | |
} | |
await fd.appendFile(']'); | |
await fd.sync(); | |
await fd.close(); | |
} | |
} catch (error) { | |
console.log('ouch'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment