Skip to content

Instantly share code, notes, and snippets.

@zignd
Last active May 10, 2020 23:34
Show Gist options
  • Select an option

  • Save zignd/b9804f71f7633ca89af23d9b34f9f4e0 to your computer and use it in GitHub Desktop.

Select an option

Save zignd/b9804f71f7633ca89af23d9b34f9f4e0 to your computer and use it in GitHub Desktop.
const fs = require("fs")
const path = require("path")
function example(message, callback) {
const filePath = path.join(process.cwd(), "callback-file-test")
const data = Buffer.from(message)
fs.access(filePath, fs.constants.F_OK, (err) => {
if (!err) {
return callback(new Error("can't proceed, the file exists"))
}
fs.writeFile(filePath, data, (err) => {
if (err) {
return callback(new Error(`failed to write to the file: ${err.message}`))
}
callback(null, filePath)
})
})
}
const message = `Walking the edges of reality, is it just me?`
example(message, (err, filePath) => {
if (err) {
console.error(new Error(`something unexpected happened: ${err.message}`))
return
}
console.log("Successfully wrote to the file at", filePath)
})
// $ node callback.js
// Successfully wrote to the file at /home/zignd/code/error-handling-nodejs/callback-file-test
// $ node callback.js
// Error: something unexpected happened: can't proceed, the file exists
// at /home/zignd/code/error-handling-nodejs/callback.js:26:23
// at /home/zignd/code/error-handling-nodejs/callback.js:10:20
// at FSReqCallback.oncomplete (fs.js:155:23)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment