Node Js course – 4 Module system

Hi, the module “File system” that is going to allow us to access the operating system file system, we will be able to read and write open files, check if some file or directory exist.

In this link we can find the documentation about the file system.

Creating a file with file system module

We are going to use the “writeFileSync” method to create a file and insert some data, so at the the first time if the file doesn’t exist the file will be created, but if the file exist then just the text will be replaced in the file. 

The file that will be created is “note.txt” and the text that will be inside that file will be “My name is Cristina Rojas”.

// Dependencies
const fs = require('fs'); // File system module, that is part of Node.js
 
// Creating node.txt file and writting some note inside that file
fs.writeFileSync('note.txt', 'My name is Cristina Rojas');

And we need to run the “node app.js” command in the terminal to see the result.

Result:

Append new text to existing file

To do that we need to use the “appendFileSync” method, the first parameter will be the existing file name and the second parameter will be the new text.

// Append new text to a existing file
fs.appendFileSync('note.txt', ' Thanks for visit my blog!');

Result:

By Cristina Rojas.