Core Node Package for Reading and Writing Files

Yesterday, I answered my ain SUPER-NOOB questions near servers and NodeJS. Today, I want to take a look at how nosotros can apply a core module within NodeJS which allows us to interact with the file system. This core module is called fs (file system).

Let's have a look at some of the simplest operations we tin can achieve using fs.

A note about asynchronous code

If you aren't already familiar with Promises and the concept of asynchronous code, it is probably best to use the 'Sync' versions of all of the following methods. I won't be covering them here, because they're not what I'thou learning, but y'all can check the NodeJS documentation for more data.

If y'all kinda become the thought of Promises and/or asynchronous callbacks, and so you lot will probably be fine to get through this.

Asynchronous callbacks in NodeJS

Each of the following methods follows a similar pattern:

  1. The method/function itself, e.g.fs.readFile(
  2. The file or binder it will be working with (aka the path), due east.g. './file.txt',
  3. Additional options, due east.k. {flag: "a"},
  4. A callback function e.m. (err) => panel.log(err ? err : "success"))

Since all of the following methods are asynchronous, the callback function is what volition run after the method is complete. It unremarkably takes either i or ii parameters, and in all cases listed here, the first parameter is the error bulletin if a problem is encountered.

Now that we've covered the nuts, allow's accept a await at how we tin make a new directory.

Setting up a path variable

For the sake of my examples beneath, I put some nice little code at the superlative of my file which looks similar this:

                          const              fs              =              crave              (              "              fs              "              );              const              path              =              require              (              "              path              "              );              allow              currentPath              =              path              .              dirname              (              __filename              );                      

Enter fullscreen fashion Exit fullscreen fashion

The get-go two lines import the core module native to NodeJS which we demand, and then the 3rd line accesses the file we're in (a unproblematic alphabetize.js file) and then pulls out the path into its directory using path.dirname every bit the method, and the global variable __filename.

By creating the currentPath variable, I can more easily examination and play with the following methods. If y'all don't want to practise this or something similar, you can also manually enter the path into the directory in which you lot want to piece of work. Personally, I feel this is easier.

Now, it's important to note that we don't always need to use the electric current path/directory in our methods. We could simply utilize ./ or similar, however as I see it, in future we are probable to be needing to work with other paths outside of our source lawmaking, so I presume (perhaps wrongly?) that using the full path is a meliorate addiction to build. I'd exist interested to hear what more experienced developers think nigh this in the comments!

Using fs.mkdir to Create a Directory

The following command merely creates a new directory called testFolder within our current binder. Using a template literal i.east. a cord with backticks\ nosotros tin insert our currentPath into our first argument.

                          fs              .              mkdir              (              `              ${              currentPath              }              /testFolder`              ,              (              err              )              =>              {              if              (              err              )              throw              err              ;              });                      

Enter fullscreen mode Exit fullscreen fashion

Using fs.readdir to Check the Contents of a Directory

You may be familiar with the ls control in the Terminal. This is a similar control, yet rather than providing us with a CLI read-out of the files, it returns an array of file and folder names.

                          fs              .              readdir              (              currentPath              ,              (              err              ,              files              )              =>              {              if              (              err              )              throw              err              ;              console              .              log              (              files              );              });                      

Enter fullscreen mode Leave fullscreen mode

When I ran this in my test file, this is what I got back:

                          [              '              index.js              '              ,              '              test.txt              '              ,              '              testDir2              '              ,              '              testDir3              '              ,              '              testsDir3              '              ]                      

Enter fullscreen manner Exit fullscreen mode

Additionally, there is a way to become access to what type of file is in your directory. Here's a neat little function I came upwardly with:

                          fs              .              readdir              (              currentPath              ,              {              withFileTypes              :              true              },              (              err              ,              files              )              =>              {              if              (              err              )              throw              err              ;              files              .              forEach              ((              entry              )              =>              {              console              .              log              (              `              ${              entry              .              name              }              ,                            ${              entry              .              isDirectory              ()              ?              "              directory              "              :              "              file              "              }              `              );              });              });                      

Enter fullscreen fashion Exit fullscreen way

This will allow me to see in my console, whether each item is a directory or a file, using another inbuilt method in Node (I am starting to love all these in-builts!) called isDirectory() which comes back on file listings when the withFileTypes: true object is passed in every bit an optional second argument.

So what practise we become dorsum?

                          index              .              js              ,              file              test              .              txt              ,              file              testDir2              ,              directory              testDir3              ,              directory              testsDir3              ,              directory                      

Enter fullscreen manner Go out fullscreen fashion

### Using readFile to Expect at File Contents

Let'due south say nosotros want to look within the examination.txt file and see what it says. Unfortunately, data from this file is going to come in encoded. Let me show y'all what I hateful:

                          fs              .              readFile              (              `              ${              currentPath              }              /textInfo.txt`              ,              (              err              ,              data              )              =>              {              if              (              err              )              throw              err              }                      

Enter fullscreen style Get out fullscreen way

Here's what we get back

            <Buffer 54 68 69 73 20 66 69 6c 65 20 69 73 20 62 79 20 41 6e 6e 61 20 4a xx 4d 63 44 6f 75 67 61 6c 6c 21 21 21>                      

Enter fullscreen mode Exit fullscreen mode

Uhhh... OK. Well, that's not normal, readable text. WHAT DOES IT MEAN?

Luckily, we tin can specify what format to employ to decode/parse this information. In the case of elementary text, utf-eight, which we come across entered here as a 2nd parameter in string format.

                          fs              .              readFile              (              `              ${              currentPath              }              /textInfo.txt`              ,              '              utf8              '              ,              (              err              ,              data              )              =>              {              if              (              err              )              {              console              .              error              (              "              ERROR: File reading did not work. Mistake code                            "              +              err              )              }              else              {              console              .              log              (              "              SUCCESS! Here is your data:                            "              +              information              )              })                      

Enter fullscreen mode Exit fullscreen style

Now what do we get??

            This file is by Anna J McDougall!!!                      

Enter fullscreen mode Exit fullscreen mode

Whew, that makes a lot more sense.

Using writeFile to Create a New File or Suspend Text

Now that yous're familiar with the pattern of these commands, let's have a look at a simple case where we create or overwrite a text file:

                          const              newText              =              "              Here is some new text!              "              fs              .              writeFile              (              `              ${              currentPath              }              /textInfo.txt`              ,              content              ,              (              err              )              =>              {              if              (              err              )              throw              (              err              )              })                      

Enter fullscreen manner Exit fullscreen way

Great! We now accept a file called textInfo.txt which has the text "Hither is some new text!" within it. Let's effort to add some More than text!

                          const              newText2              =              "              \n              I'm so glad we're adding more than text              "              ;              fs              .              writeFile              (              `              ${              currentPath              }              /textInfo.txt`              ,              newText2              ,              (              err              )              =>              {              if              (              err              )              throw              err              ;              });                      

Enter fullscreen manner Leave fullscreen style

Skilful piece of work! ...Wait, that's not right...

image.png

Where did our starting time text go? D'oh! That's right! fs.writeFile overwrites existing file contents! Then how can nosotros just add some more text onto the cease of our original instead? Using the a flag.

                          const              newText2              =              "              \northward              I'chiliad then glad we're adding more than text              "              ;              fs              .              writeFile              (              `              ${              currentPath              }              /textInfo.txt`              ,              newText2              ,              {              flag              :              "              a              "              },              (              err              )              =>              {              if              (              err              )              throw              err              ;              });                      

Enter fullscreen way Exit fullscreen manner

Aha! Well that looks much amend:

image.png

Using fs.stat to Check Your File Details

Final simply not least, allow's accept a footling peek in at our file to come across what its details/stats are. Here's a fun trivial method:

                          fs              .              stat              (              `              ${              currentPath              }              /textInfo.txt`              ,              (              err              ,              stats              )              =>              {              if              (              err              )              throw              (              err              )              console              .              log              (              stats              )              }                      

Enter fullscreen mode Get out fullscreen mode

This brings the states back the following information:

            Stats {   dev: 647735127,   manner: 33206,   nlink: i,   uid: 0,   gid: 0,   rdev: 0,   blksize: 4096,   ino: 44754521297123880,   size: 0,   blocks: 0,   atimeMs: 1609859928899.2424,   mtimeMs: 1609859928899.2424,   ctimeMs: 1609859928899.2424,   birthtimeMs: 1609859583171.8276,   atime: 2021-01-05T15:18:48.899Z,   mtime: 2021-01-05T15:eighteen:48.899Z,   ctime: 2021-01-05T15:18:48.899Z,   birthtime: 2021-01-05T15:xiii:03.172Z }                      

Enter fullscreen mode Exit fullscreen way

Wonderful! Now we have a whole heap of details most our text file. I'g certain i day we'll exist able to understand and use this information somehow!

housecumeneamord.blogspot.com

Source: https://dev.to/annajmcdougall/reading-and-writing-files-directories-in-nodejs-using-the-fs-core-module-225c

0 Response to "Core Node Package for Reading and Writing Files"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel