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.
 

35 lines
790 B

const fs = require('fs');
const read_file = (fname, events) => {
let noop = () => {};
let onStat = events.onStat || noop;
let onOpen = events.onOpen || noop;
let onRead = events.onRead || noop;
fs.stat(fname, (err, stats) => {
onStat(stats);
fs.open(fname, 'r', (err, fd) => {
onOpen(fd);
let inbuf = Buffer.alloc(stats.size);
fs.read(fd, inbuf, 0, stats.size, null, (err, bytesRead, buffer) => {
onRead(bytesRead, buffer);
});
});
});
}
read_file('test.txt', {
onRead: (bytesRead, buffer) => {
console.log(`Read ${bytesRead} bytes: ${buffer.toString()}`);
},
onStat: (stat) => {
console.log(`Got stats, file is ${stat.size} size.`);
},
onOpen: (fd) => {
console.log(`Open worked, fd is ${fd}`);
}
});