Skip to content

Instantly share code, notes, and snippets.

@kieranbarker
Last active November 1, 2021 08:55
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/e81e9664bcb917a7f11cff5a86551219 to your computer and use it in GitHub Desktop.
Save kieranbarker/e81e9664bcb917a7f11cff5a86551219 to your computer and use it in GitHub Desktop.
Asynchronously read and write files in Node.js.
{
"name": "read_write",
"version": "1.0.0",
"description": "Asynchronously read and write files.",
"private": true,
"main": "read_write.js",
"type": "module",
"scripts": {
"start": "node read_write.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Kieran Barker <kieran@barker.codes> (https://barker.codes/)",
"license": "MIT"
}
import * as fs from 'fs';
import * as fsPromises from 'fs/promises';
//
// Read
//
// Callback API
fs.readFile('./package.json', 'utf8', (error, data) => {
if (error) {
throw error;
} else {
console.log(data);
}
});
// Promises API
// fsPromises
// .readFile('./package.json', 'utf8')
// .then(console.log)
// .catch(console.error);
//
// Write
//
const file = 'hello_world.txt';
const data = 'Hello, World!';
// Callback API
fs.writeFile(file, data, 'utf8', error => {
if (error) {
throw error;
} else {
console.log(`Successfully wrote '${data}' to ${file}.`);
}
});
// Promises API
// fsPromises
// .writeFile(file, data, 'utf8')
// .then(() => console.log(`Successfully wrote '${data}' to ${file}.`))
// .catch(console.error);
@kieranbarker
Copy link
Author

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