Skip to content

Instantly share code, notes, and snippets.

@kieranbarker
Last active Nov 1, 2021
Embed
What would you like to do?
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

kieranbarker commented Nov 1, 2021

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