Reading and writing files is from the first requirement of programming. When it comes to a point you will probably have to code. When I started to computer engineering our first-week assignments include reading and writing from file and includes some calculations. From then in my jobs and project, i often need reading and writing from the filesystem.

I genuinely love to use javascript. It’s my first personal choice for when I need to create some scripting solution for my tasks. In this post, I want to show you some file operations showed million times in different blog posts.

For interacting with a file system with nodejs we need to use fs module. There are sync and asynchronous way to these operations.

  • fs

    const fs = require('fs')
    
  • readFileSync

    const data = fs.readFileSync('meaingful_data.txt')
    
  • readFile(path,config,callback)

    fs.readFile(filePath, {encoding: 'utf-8'},(err,data) => {
      if (!err) {
        console.log('Receive data: ' + data); // Do your job
      } else {
        console.log(err); // Handle Error
      }
    });
    

There is a disadvantage of using readFile and readFileSync these methods buffer all files into memory. If we want to minimize our memory usage we need to use streams.

  • writeFileSync

    fs.writeFile('huge_volume_data.txt', 'Users data volume usage!',(err) => {
      if (err) return console.log(err);
      console.log('Users data volume usage written to huge_volume_data.txt');
    });
    
  • writeFile

    fs.writeFile('huge_volume_data.txt', 'Users data volume usage!');
    

These methods are more searched methods for nodejs filesystem in google trends when I writing this blog. fs is a huge module and there is much more than this you can do almost all POSIX standard operations.

Google Trends
Google Trends for nodejs fs

For example, if need access time off and the file we can do with Stats in POSIX standard access time defined in sys/stat.h st_atime. We can easily achieve access time with ls -lu in the command line. and with nodejs, we need to obtain stats object for a path.

const fs = require("fs")
let stats = fs.lstatSync("user_info.dat") // Return Stats object
console.log(stats.atime) //2020-08-14T21:42:47.747Z Access Time

And also we can check other properties of a path like if its directory, file, socket, or symlink link.

  console.log(stats.isFile()) //true
  console.log(stats.isSocket()) // false
  console.log(stats.isSymbolicLink()) // false
  console.log(stats.isDirectory()) // false

For this blog post, I want to show a sample code for reading a file using streams. These examples are read from stream byte by byte and log file in every line.

  • createReadStream

    const fs = require("fs");
    const readStream = fs.createReadStream("user_info.dat");
    readStream.on('readable', () => {
      let line, chunk;
      while (null !== (chunk = readStream.read(1))) { // Each time read one byte one character continue if chunk not null
        if (chunk != '\n') {
          line += chunk // store each byte in another object
        } else {
          console.log(line);
          line = '' // clear line for next line
        }
      }
    });