Created
May 10, 2017 01:37
-
-
Save styfle/ac0308df736fad87dd4b9eb8827df801 to your computer and use it in GitHub Desktop.
Promises in Node.js 8.x Core
This file contains hidden or 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
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