Nodejs fs write to file tutorial

Basic guide on how to use node.js fs to write to file.

Prologue

Node.js provide a code library called fs to manipulate files, like writing and reading utilities, in this simple tutorial we are going to write contents on some files.

Write to file with fs.writeFile

Suppose we have a project structure like this one:


- index.js // file
- /contents // folder
    - foo // file
    

project structure

We would like to write contents in foo through a script placed in index.js and we can easily achive that by doing:

const fs = require('fs');

fs.writeFile('./contents/foo', 'file contents', err => {
  if (err)
    console.log(err);
});

fs write to file

Thinks to know about fs.writeFile:

  • The first argument is the relative path to the file you want to write in;
  • The second one is the actual contents to write;
  • The third argument is a callback function since writeFile is asynchronous;
  • Also take care that writeFile replaces the content, to append new text on a file you can use appendFile.

Append to file with fs.appendFile

Append data to a file is just like write to it, as shown in this example

const fs = require('fs');

  fs.writeFile('./contents/foo', 'file contents', writeErr => {
    if (!writeErr)
      fs.appendFile('./contents/foo', 'more file contents !', appendErr => {
        if (appendErr)
          console.log(appendErr);
      });
    else
      console.log(writeErr);
  });
  

fs append to file

Here fist we write some contents in the foo file like we did in the previous example, then we add some other content to it using fs.appendFile. Finally note that all code is asynchronous in order to obtain better performance.

Remember to checkout also my other tutorial on nodejs fs read file.

You may also like

Node.js flat CMS Tutorial with Enduro.js

A tutorial on how to get started with with Enduro.js, a Node.js flat CMS.

Tags: Node.js CMS

Read more

Node.js flat CMS Tutorial with Enduro.js - Part Two

Second part of a tutorial on how to get started with with Enduro.js, a Node.js flat CMS.

Tags: Node.js CMS

Read more

Frontend pipeline with webpack 2: setting up babel (1 of 2)

An introduction about frontend pipeline in 2017 and how to build one from scratch using webpack 2: setting up babel traspiler.

Tags: webpack 2

Read more
See all