//set up: //Basics: console.log(__dirname); //It will return the absolute path for current folder. console.log(__filename); //It will return the absolute path for current folder with file name. --------------------------------------------------- // Modeles | Require let data = require("./script"); /* :> './' will look for relative to current path, 'require(".fileName") Will return the object.' */ module.exports = { var1, var2 } // We can export multiple things/variables. let { people } = require("./totalPeople"); // It will only return the 'people' variable in 'totalPeople'. let { people, age } = require("./totalPeople"); // It will only return the 'people' and 'age' variables in 'totalPeople'. // Also called Destructuring. --------------------------------------------------- let os = require("os"); //Will provide built in Operating System module( object). console.log(os.platform()); //Will return the type of OS ( windows/Linux...); console.log(os.homedir()); //It will provide the HOME directory --------------------------------------------------- const fs = require("fs"); //Built in module, Used to read/write the files. ( FILE SYSTEM ) // Reading Files fs.readFile(('./R/text.txt'), ( error, data ) => { console.log("Data: ", data); // It will return a package as a Buffer. console.log(data.toString()); // It will provide the data (text.txt) in readable format. }); //'readFile' is an async function and will not block the execution. // Writing Files fs.writeFile('./R/text.txt', " This is new replaced data, ", ( ) => { //If the address is not valid, It will create the file. // It will replace the old data. //Since it's Async function, Call back function is required. console.log("Data updated"); }); //'writeField' is an asyn function and will not block the execution. // Directories //create fs.mkdir('./assets',(err)=>{ if(err) { console.log("Error: ",err) } console.log("Folder created"); }) //Remove fs.rmdir('./assets',(err)=>{ if(err) { console.log("Error: ",err) } console.log("Folder Removed"); }) //Check if specific 'folder' exist or not. if(fs.existSync("./Resources")){ //Check if 'Resources' folder is there or not. //'existSync' is a sync function and will block the code. //code } ** //Check for folder 'R' using '!'. if(!fs.existsSync('./R')){ console.log(" R Folder does not exists"); //Create Folder. fs.mkdir('./R',(err)=>{ if(err){ console.log("Issue with creatin Folder") }; console.log("Folder R created") }) }else { //If already there, then deleting 'R' Folder fs.rmdir("./R",(err)=>{ if(err){ console.log("issue with deleting Folder") } console.log("Folder R Deleted.") }) } ** // Deleting Files fs.unlink("./R/text.txt", (err)=>{ console.log("Issue with deleting File"); console.log("File has been deleted.") }) //We should always check first if 'folder'/'files' exist or not. if(fs.existsSync("./R")){ console.log("Folder 'R' does exist"); //Code } if(fs.existsSync("./R/file.txt")){ console.log("File 'file.txt' does exist"); //Code } ** //Summary //Import Modules const http = require("http"); const fs = require("fs"); //Creating Server const server = http.createServer((req, res)=>{}) //Read File. fs.readFile("./R/blogData.txt",(err,data)=>{ }) //Writing Files fs.writeFile("./R/newFile4", "To a worm in horseradish, The world is horseradish.", (error)=>{ // console.log("File Updated.") }) //Create Directories. fs.mkdir("./R/newFile5",(error)=>{}) //Check the Folder/File console.log(fs.existsSync("./R/newFile2")); //Remove Folder fs.rmdir("./R/NewFolderCreated",(error)=>{ }) //Deleting File fs.unlink("./R/newFile2",(error) =>{ }) //Server Configuration. server.listen(8080 ,"localhost",()=>{}); ** --------------------------------------------------- //Streams and Buffers. Stream : Start using data, Before it has finished loading. Data will be transferred as 'Buffers'. ** //Create/Read new Stream let createStream1 = fs.createReadStream("./R/sampleData.txt"); //Address should be mentioned. /* We can pass the 2nd argument as '{ encoding: "utf8" }', and this we don't have to use 'toString()'. let createStream1 = fs.createReadStream("./R/sampleData.txt",{encoding:"utf8"}); */ createStream1.on("data",(bufferData)=>{ //'on' is event listener, //'data' is type of event. ( example 'click','scroll') console.log(bufferData.toString()); //Every time we get new buffer, This 'bufferData' will be called ( call back function.) }) ** //Write Stream ** let createStream = fs.createReadStream("./R/sampleData.txt", { encoding:'utf8'}); let writeStream = fs.createWriteStream('./R/blogData.txt');//if address does not exist, It will create new one. writeStream.write('First Line Here...'); // It will write the provided text in './R/blogData.txt' createStream.on("data",(buffer)=>{ //For every 'buffer' generated, It will passed on to 'writeStream' writeStream.write('\n'); writeStream.write("Some Data"); writeStream.write('\n'); writeStream.write('\n'); writeStream.write( buffer ); }) writeStream.write('Last Line Here....'); ** //OR ** //Streams and buffers. let createStream = fs.createReadStream("./R/sampleData.txt", { encoding:'utf8'}); let writeStream = fs.createWriteStream('./R/blogData.txt'); writeStream.write("First Line..."); //Using 'PIPE' createStream.pipe(writeStream); //It will automatically pass all the data to './R/blogData.txt'. from "./R/sampleData.txt". ** --------------------------------------------------- //Client and Servers const http = require("http"); const server = http.createServer((req, res)=>{ console.log("Request Made") }); server.listen( 3000 , 'localhost' ,()=>{ // 'localhost' is by default. console.log("Server is Live on Port 3000") }) --------------------------------------------------- //Requests and Responses. ** const server = http.createServer((req, res)=>{ console.log("Request Made") console.log(req.url); //It will provide the 'url'. Root url is '/'. console.log(req.method); //It will return the method used. }); ** ** const server = http.createServer((req, res)=>{ //Set Header Content Type. res.setHeader("Content-type", "text/plain"); //It will tell browser what kind of content to expect. It can '"text/html"', If we want to pass on HTML content/tags. res.write(" Hello Karan"); res.end(); //Manually end it. This will send the response to the browser. }); ** ** //Linking HTML file to the Code. let fs = require("fs"); const server = http.createServer((req, res)=>{ res.setHeader("Content-type", "text/html"); //'text/html' is used, This time we will passing data as a HTML content ( with Tags nd all); fs.readFile('./home/Index.html',(err, data)=>{ if(err){ console.log("Koi Panga", err); res.end(); //If err then we want to end the response, So that browser will move with next step ( other wise it will struck on loading ) }else { res.write(data); //We are passing 'index.html' as the data. res.end(); //We can also use 'res.end(data)'(for single file). ( res.write() will not be needed. ) } }) res.write(" Hello Karan"); res.end(); //This will send the response to the browser. }); ** //Routes ** const server = http.createServer((req, res)=>{ console.log("URL: ", req.url) let path = "./"; // Root will always be './' switch( req.url ){ case '/': path += 'index.html' break; case '/about': path += "about.html"; break; default : path += "404.html"; //This we can add specific page } //Header Content. res.setHeader("Content-type", "text/html"); fs.readFile(path,(err, data )=>{ //Depending upon the URL, It will return the required HTML/plain page. res.write(data); res.end(); }) }); ** //Status Codes 200 - OK 301 Resource moved 404 Not Found 500 Internal serval error ------------------------------------------------- --------------------------------------------------- --------------------------------------------------- --------------------------------------------------- ------------------------------------------------- --------------------------------------------------- --------------------------------------------------- ---------------------------------------------------
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter