Last active
November 8, 2021 09:09
-
-
Save kieranbarker/b7facbb4e58a5de90baeaa789628234d to your computer and use it in GitHub Desktop.
Asynchronously append data to a file in Node.js.
This file contains 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
import * as fs from 'fs'; | |
import * as fsPromises from 'fs/promises'; | |
const file = 'hello_world.txt'; | |
const data = 'Hello, World!'; | |
// | |
// Callback API | |
// | |
fs.appendFile(file, data, 'utf8', error => { | |
if (error) { | |
throw error; | |
} else { | |
console.log(`Appended string "${data}" to ${file}.`); | |
} | |
}); | |
// | |
// Promises API | |
// | |
// fsPromises | |
// .appendFile(file, data, 'utf8') | |
// .then(() => console.log(`Appended string "${data}" to ${file}.`)) | |
// .catch(console.error); |
This file contains 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
{ | |
"name": "append_file", | |
"version": "1.0.0", | |
"description": "Asynchronously append data to a file.", | |
"private": true, | |
"main": "append_file.js", | |
"type": "module", | |
"scripts": { | |
"start": "node append_file.js", | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "Kieran Barker <kieran@barker.codes> (https://barker.codes/)", | |
"license": "MIT" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Read the blog post.