Skip to content

Instantly share code, notes, and snippets.

@chadbr
Last active May 1, 2019 01:51
Show Gist options
  • Save chadbr/b21ac6ee49a8955fb062267e401a2aea to your computer and use it in GitHub Desktop.
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
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