nic_training
Version:
Sample demos for training on nodejs
45 lines (40 loc) • 1.39 kB
JavaScript
//CoreModules.js
var http = require("http");//http is a core module that allows to handle http requests made by the user...
var fs = require("fs");
/******************Using http***************************
function postErrorPage(res){
res.writeHead(404,{'Content-type':'text/text'})
res.write("Oops! Some thing happened. Will come back to U");
res.end();
}
http.createServer(function(req, res){
if(req.method == 'GET' && req.url =='/'){
console.log(req);
res.writeHead(200, {'Content-type':'text/html'});
fs.createReadStream("./HomePage.html").pipe(res);
}else{
postErrorPage(res);
}
}).listen(1234);
******************Using file system************************/
function readFile() {
fs.readFile('firstExample.js', 'utf8', function(err, res){
if(err){
console.log(err.message);
}else{
console.log(res)
}
});
}
//readFile is used to read a file asynchronously. It has a callBack function that can be used to read the data after the file is read.
fs.open('MyFile.txt','a+', function(err, fd){
var buffer = new Buffer("Sample Content to add");
fs.write(fd, buffer, 0, buffer.length, null, function (err, written) {
console.log(written);
fs.close(fd, ()=>console.log("Completed"));
});
});
/*var contents = fs.readFileSync('modules.js', 'utf8');//File reading synchronously...
console.log(contents);
readFile();
*/