Sample Video Frame
09: Files
I am going to show you the simplest way to read something from a file, but this is definitely not the only way nor is it the best way. JavaScript is rather obsessed with many ways to read data, but before you can understand them you need to learn about functions. Functions come later in the book, so for now I'll show you how to just pull in all of a file in one move and then play with it.
The Code
You can read the documentation for the file Application Programmer Interface (API) at https://nodejs.org/api/fs.html, but don't get discouraged if this makes zero sense. Just glance through it and know it exists.
// https://nodejs.org/api/fs.html
const fs = require("fs");
let contents = fs.readFileSync("test.txt");
console.log("Contents:");
console.log(contents.toString());
// using a callback
console.log("----------------------");
fs.readFile("test.txt", (err, data) => {
console.log(data.toString());
});
The first part of this code has the easy way to read a file using fs.readFileSync(). This just pulls the entire file into your program and puts it into the contents variable.
The second part after the comment // using a callback is the more complicated but normal way that most JavaScript programmers would read a file. This way is much more complex, so I left the description in the video for this exercise.
If you type this code in, and still have no idea what lines 12-14 are doing, then don't despair. We will go over this concept many times in the next exercises.
Register for The Pro-Webdev Mega Bundle
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.