4) Program to read a file from node.js
const fs = require ('fs');
fs.readFile('./test.txt','utf8', (err, data) => {
if (err) {console.error(err); }
console.log ("Data is: "+data);
});
4) Program to read a file from node.js
const fs = require ('fs');
fs.readFile('./test.txt','utf8', (err, data) => {
if (err) {console.error(err); }
console.log ("Data is: "+data);
});
3) Create a new text file from Node.js
var fs = require ('fs'); // include pre-built node file stream module
var data = "Creating a new file";
fs.writeFile('newFile.txt', data, function (err){
if (err) throw err;
console.log (" File created successfully"};
});
Run the program in the terminal:
$ node createNewFile.js
File created successfully
2) Program to create a node module
Let us create a Calculator.js file with add, subtract, and multiply functions ->
// Addition of two numbers
exports.add = function (x, y){
return x+y;
}
// Subtraction of two numbers
exports.subtract = function (x, y){
return x-y;
}
// Multiply of two numbers
exports.multiply = function (x,y){
return x*y;
}
Let us create a new node file to call these functions ->
var calc = require ('./Calculator.js')
var x = 15, y= 10;
console.log (" Addition of two numbers is: "+ calc.add (x,y));
console.log (" Subtraction of two numbers is: "+ calc.subtract (x,y));
console.log (" Multiplication of two numbers is: "+ calc.multiply (x,y));
===OUTPUT===
Addition of two numbers is: 25
Subtraction of two numbers is: 5
Multiplication of two numbers is: 150
## Program to create a server in node.js language ##
var http = require ('http');
http.createServer( function (req, res) {
res.writeHead (200, {'Content-type': 'text/plain'});
res.end ('Hello World!!');
}).listen (8080);
===OUTPUT===
Hello World!!