Read and Write files in Node.js
Hey all...! This article will help you to know how to read and write files in Node.js. For this first of all we will create a small text file called hello.txt in our project folder and add a text in to it.
For reading and writing modules we want to load one of the core modules which is known as fs in node modules. Lets require it in our working file as we did in previous articles.
var fs = require('fs');
Then you have to read the file by using the following code.
var readme=fs.readFileSync('hello.txt','utf8'); //blocking the code until we completing reading the filename
console.log(readme);
In the above code readFileSync is the method that we use to read a file.As you can see inside the parameters I have written the file name and utf8. as the file is read in binary that means using 1s and 0s to convert it we use utf8. When you run the command line, you can read the hello.txt file.
var fs = require('fs');
fs.readFile('hello.txt','utf8',function(err,data){
console.log(data);
});
//code
console.log('the code here');
If you compare with the previous code I have removed the sync in readfilesync and also created a function to read the data int the file. If you run the command line, you may first get the output of the code below the reading code while it is being read .
Writing a File
Same as we read the file we can write a new file to our project.The code for writing a new file is given below.
var writeme=fs.writeFileSync('write.txt',readme);
In here we have used the function writeFileSync to write the function. Inside the parameters 'write.txt' is the new file that we create and readme is the file that we get the text.
Comments
Post a Comment