Last active
November 1, 2021 08:55
-
-
Save kieranbarker/e81e9664bcb917a7f11cff5a86551219 to your computer and use it in GitHub Desktop.
Asynchronously read and write files in Node.js.
This file contains hidden or 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": "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" | |
} |
This file contains hidden or 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'; | |
// | |
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Read the blog post.