Skip to content

Instantly share code, notes, and snippets.

@styfle
Created May 10, 2017 01:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save styfle/ac0308df736fad87dd4b9eb8827df801 to your computer and use it in GitHub Desktop.
Save styfle/ac0308df736fad87dd4b9eb8827df801 to your computer and use it in GitHub Desktop.
Promises in Node.js 8.x Core
const promisify = require('util').promisify;
const fs = require('fs');
const stat = promisify(fs.stat);
const writeFile = promisify(fs.writeFile);
const appendFile = promisify(fs.appendFile);
async function exists(f) {
try {
const stats = await stat(f);
return true;
} catch (e) {
return false;
}
}
async function main() {
const filename = './example.txt';
const timestamp = new Date().toISOString();
const fileExists = await exists(filename);
if (fileExists) {
try {
await appendFile(filename, `Updated file on ${timestamp}\n`);
console.log('Successfully updated file');
} catch(e) {
console.err('Failed to update file');
}
} else {
try {
await writeFile(filename, `Created file on ${timestamp}\n`);
console.log('Successfully created file');
} catch (e) {
console.err('Failed to create file');
}
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment