Reading and writing files with node.js

Introduction:

In the previous blogs, we have already seen what exactly node.js is and what do they even come into existence. This article covers various API usage for reading and writing files in node.js. 

                                                             greg monroe page GIF

                                                                    Source: giphy

 

Confusing right!! Let’s catch it with a little more closeness.

 

Reading files with node.js

 

A lot of different ways are possible for reading files in node.js. The simplest way to do the same is to use fs.readFile() API. In this method, the file path is passed, and encoding and decoding functions are called along the file data.

 

const fs = require('fs')

fs.readFile('/User/codingNinja/demo.txt''utf8' , (err, data) => {
  if (err) {
    console.error(err)
    return
  }
  console.log(data)
})

 

The synchronous version fs.readFileSync() can also be used.

 

const fs = require('fs')

try {
  const data = fs.readFileSync('/User/codingNinja/demo.txt''utf8')
  console.log(data)
catch (err) {
  console.error(err)
}

 

Here, both the API fs.readFile() and fs.readFileSync(), reads the full content of the memory first before returning the data. 

This creates one disadvantage of reading file methods in node.js. Big files will have significant consumption on memory usage and the speed to the overall execution of the program.

 

Hence, the better option is to prefer using streams for reading the files.

 

Writing files with Node.js

The easiest way to write files with node.js is using fs.writeFile() API. Let’s take an example for better understanding,

 

const fs = require('fs')

const content = 'Some content!'

fs.writeFile('/User/codingNinja/demo.txt', content, err => {
  if (err) {
    console.error(err)
    return
  }
  // File written successfully.
})

 

fs.writeFileSync() can also be used for writing files with node.js.

 

const fs = require('fs')

const content = 'Some content!'

try {
  const data = fs.writeFileSync('/User/codingNinja/demo.txt', content)
  //file written successfully
catch (err) {
  console.error(err)
}

 

This API will, by default, replace all the previous contents(if it is contained). But this default can be changed by specifying a flag.

 

s.writeFile('/User/codingNinja/demo.txt', content, { flag: 'a+' }, err => {})

 

The commonly used flags are:

  • r+: this flag is used to open files for reading and writing purposes.

 

  • w+: this flag is used to open files for reading and writing, and position the stream at the beginning of the file. If the file doesn’t exist, it creates one for the same.

 

  • a: this flag is used to open the file for writing and position the stream at the end of the file. This flag also creates a file program's overall execution if the file does not exist.

 

  • a+: this flag is used to open the file for reading and writing and position the stream at the end of the file. The file gets created if it doesn’t exist.

 

Appending to a file

One easy method to append content to the end of the file is using fs.appendFile() and its fs.appendFileSync() counterpart.

 

const content = 'Some content!'

fs.appendFile('fileDemo.log', content, err => {
  if (err) {
    console.error(err)
    return
  }
  // Done!
})

 

Using streams

The above-defined methods write the entire content to the file, even before returning the program’s control to itself. In async methods, such a scenario is preferred as a callback.

A better option is to move towards writing the contents of the file using streams. 

 

Frequently asked questions

 

  1. Express error handling in Node.js?

 

Error handling is the way to express catches and process errors. It is done in both synchronous and asynchronous ways. Express has its error handler, so we don’t need to write on our own.

2. Await throws an error. Justify the statement.

 

If any promise fails to resolve typically, then await cannot return the result. In such cases, await throws an error.

 

3. Is node.js a programming language?

 

No, node.js is not a programming language. But, it makes use of javascript, which is a programming language. It also helps web developers to play and build web applications.

4. Name some uses of node.js?

 

The uses of node.js are:

  • Server-side programming
  • Deployed for non-blocking
  • Creating and deleting server files.

 

Key takeaways:

In this article, we have learned about various APIs which help read and write files with node.js. We have seen closely how API allows in our code with multiple examples.

Keeping the theoretical knowledge at our fingertips helps us get about half the work done. To gain complete understanding, practice is a must. To gain a thorough understanding, visit our page.
 

~ By: Pradipta Choudhury

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think