Skip to content

Instantly share code, notes, and snippets.

@styfle
Created May 10, 2017 01:34
Show Gist options
  • Save styfle/80454c67c2d6fbed83769c529b615350 to your computer and use it in GitHub Desktop.
Save styfle/80454c67c2d6fbed83769c529b615350 to your computer and use it in GitHub Desktop.
Promises in Node.js 8.x Core
const fs = require('fs');
function exists(f, callback) {
fs.stat(f, (err) => {
callback(err ? false : true);
});
}
function main() {
const filename = './example.txt';
const timestamp = new Date().toISOString();
exists(filename, (fileExists) => {
if (fileExists) {
fs.appendFile(filename, `Updated file on ${timestamp}\n`, (err) => {
if (err) {
console.err('Failed to update file');
} else {
console.log('Successfully updated file');
}
});
} else {
fs.writeFile(filename, `Created file on ${timestamp}\n`, (err) => {
if (err) {
console.err('Failed to create file');
} else {
console.log('Successfully created file');
}
});
}
});
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment