DEV Community

Oladotun Joseph
Oladotun Joseph

Posted on

Reading and Writing Files In Node.Js Using Modules.

PREREQUISITE: Node.js, Javascript basics

Modules in node.JS are used to carry out various functions because they contain various functionalities that can be used to carry out various functions.The "fs"-file system module contains the functionality needed to complete the above task.

Reading Files

STEP 1

The first step which applies for the both reading and writing the files is to require the module “fs” module that contains the functionality necessary, then assigning it to a variable as seen below.

Assignig the module to a variable

STEP 2
The variable is then used to access the readFileSync method. readFileSync takes two parameters, the path to the content to be read and "encoding(utf-8)".

readFileSync("path","encoding")

The string content of the path can then be seen through the console.
Image description

WRITING FILES

STEP 1

The first step which applies for the both reading and writing the files is to require the module “fs” module that contains the functionality necessary, then assigning it to a variable.

STEP 2: The variable is then accessed in order to call the writeFileSync function, which has two parameters: the path to the file we're writing to, and the string that will be written there.

writeFileSync(path,”string”).

Image description

const readWrite = require("fs");

const write = readWrite.writeFileSync("path", "string to be written");

This process doesn't need to be saved to a variable because it only writes the given string to the specified directory and doesn't return anything. writeFileSync() creates the required file even if the path specified hasn't been created yet.

Top comments (0)