Reading a File Javascript

So you want to read a file from Javascript?

Really? ok, well, I do, too.

Why because I have a larger goal of being a Javascript master. I want to “spin up” apps and create fun things that will help me and help the world. I believe I can do it. This begins my journey.

Let’s go!

So first thing I create a file in my Visual Studio Code IDE.

I call mine deadset001_readfile.js

Here is where we will write the code to read the txt file.

Next I create a text file to read.

I call it Welcome.txt and write Welcome to Deadset on Success Coding! Thank you for watching.

First thing we want to do is to require the fs module. This is built in to node so you don’t have to install anything.

Do you not have Node.js? Well, go get it. No we won’t wait.

So type in to your code editor

const fs = require('fs');

Now we have access to a variable that contains all of the filesystem methods that we need to read a file from our disk.

Let’s Use it!

const welcome = fs.readFileSync('./Welcome.txt', 'utf-8');

ok, that’s it! we did it.

We read a file using javascript.

What? You don’t believe me?

Ok, I will prove it.

On the next line, type the following:

console.log('The file contains the following text: ", welcome);

ok, right click on your file in the explorer of VS code and select open in integrated terminal. This will take you to the directory where your file exists. You got Node.js, right?

Great! type into the terminal node filename.js in my case I wrote node ./deadset001_readfile.js

Now hit enter!

You should see the following out put

The file contains the following text:  Welcome to Deadset on Success Coding! Thank you for watching. 
Read a File Using Node