Node.js File System (Read and Write) (FS) 04

Video Tutorial


Working with any framework, Dev environment or library needs from you to know the basics of dealing with files opening reading and writing to files, for Node.js makes that very easy to use, it has a standard module fs which gonna allow you to manipulate files very easily.

The FileSystem (FS)

The fs module is a standard module comes preinstalled with any node’s environment, just import it and start working with files

//We use our pokemons.txt that holds the pockemons names 
fs.readFile('./pokemons.txt', 'utf8', (err, data) => {
    //When ever it reads, we log the file content 
    console.log('Pokemons: ', data);

The Reading Operation by the fs is being done asynchronously, which means node.js gonna start reading the file, but not wait till it finish it register a handler and whenever the reading or writing finishes it calls the handler works in none blocking way, if you need to work with it in a blocking way (synchronously) use the readFileSync.

Also for writing to the file (appending) we can use appendFile method

//Optionally Choose the Encoding (UTF-8)
fs.appendFile('./pokemons.txt', 'DATA HAS BEEN ADDED!   HEY THIS ME ', 'utf8', (err) => {
    //We check for Any Errors 
    if (err) console.log(err);

You can check the target file for changes.

Also, there are the open and close methods which gonna open and close an Instance of the specified file with a reading buffer and number of bytes to read and write to the file, it’s actually for more advanced usage but sometimes it is very helpful for you

let path = './pokemons.txt';
//We use it for W+ : read and write to file, create if does not exists, "w+", function(error, fd) {
  //The fd is an instance of file on the memory 
  if (error) {
    console.error("error:  " + error.message);
  } else {
    console.log("File Successfully opened " + path);

You Read the DOCS for more advanced usage.

The other helpful method is the stat, which gonna allow you to get information about the file (Size, created_at, type…)

fs.stat('./pokemons.txt', (err, stats) => {
    //Stats is open, that has all the file's info 
    console.log('Stats: ', stats);

The last thing we need on a file system is to be able to delete files or directories

//Unlink will delete the specified file, returns an error or any exception occured
fs.unlink('./pokemons.txt', (err) => {
  if(err) console.log(err);

And that is it, very simple to use API from node.js, now you can easily manipulate your files alongside a node’s app.

What’s Next

The fileSystem is a quietly challenging thing but node.js wraps this up on a very elegant API that you can easily interact with since it is cross-platform.

In the Next Tutorial, we are going to cover the implementation of a Node.js Web Server using Express Framework and using Routes, Middleware.

No Comments Yet