The code from the Learn JavaScript the Hard Way module JavaScript Level 1 exercises. This is a mirror of the code I have in the book, so if you're struggling you can use this to compare against your attempts.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

17 lines
527 B

import { promises as fs } from "fs";
const read_file = async (fname) => {
try {
let file = await fs.open(fname, 'r');
let stat = await file.stat();
let buffer = Buffer.alloc(stat.size);
let result = await file.read(buffer, 0, stat.size, null);
console.log(`Read ${result.bytesRead} bytes: ${result.buffer.toString()}`);
} catch(err) {
console.log("ERROR", err);
}
}
// This only works if your package.json has "type": "module",
// or if you name the file async.mjs.
await read_file('test.txt');