Skip to content

Instantly share code, notes, and snippets.

@kieranbarker
Last active November 8, 2021 09:09
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 kieranbarker/b7facbb4e58a5de90baeaa789628234d to your computer and use it in GitHub Desktop.
Save kieranbarker/b7facbb4e58a5de90baeaa789628234d to your computer and use it in GitHub Desktop.
Asynchronously append data to a file in Node.js.
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);
{
"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"
}
@kieranbarker
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment