Node.js Cheat Sheet
To start a new node project, type
C:\Users\jinoy\OneDrive\Desktop\MERN>npm init -y
The basic syntax of calling a function in node.js with express is :
const functionname = () => {
console.log("hello world");
}
functionname();
To call a function after every 5 seconds :
setInterval(() => {
console.log("hello");
},5000 );
To call a function only once after 4 second :
setTimeout(()=>{
console.log("test");
},4000);
To run a script.js file on terminal, type :
C:\Users\jinoy\OneDrive\Desktop\MERN>node script.js
OR
C:\Users\jinoy\OneDrive\Desktop\MERN>node script
To stop a function that is executing on every interval( time to call function again) :
const interval = setInterval(() => {
console.log("hello");
},1000 );
setTimeout(()=>{
clearInterval(interval);
console.log("stopped");
},6000);
The above function will work continously untill the clear interval is executed. i.e, print hello 5 time and stop the function and print stopped.
Note : We must store the reference of the function on a variable to to call it inside clearInterval()
Output
C:\Users\jinoy\OneDrive\Desktop\MERN>node script.js
hello
hello
hello
hello
hello
stopped
In js the console.log object is inside window i.e,
console.log("test"); == window.console.log("test");
In node, we can't use window because window can be used only on client side. Here we use global i.e,
global.console.log("test");==console.log("test");
To display the file name of the node project which is currently running :
console.log(__filename);
Output
C:\Users\jinoy\OneDrive\Desktop\MERN>node script.js
C:\Users\jinoy\OneDrive\Desktop\MERN\script.js
To display the directory name of the node project which is currently running :
console.log(__dirname);
Output
C:\Users\jinoy\OneDrive\Desktop\MERN>node script.js
C:\Users\jinoy\OneDrive\Desktop\MERN
How to import a module (also called package/library) in node ?
we can import module in node by require(). But if we need to use any function inside that module then save the module inside a constant.
const a = require("path");
console.log(a.basename(__filename));
Output
C:\Users\jinoy\OneDrive\Desktop\MERN>node script.js
script.js
Here we imported path module and used the function basename() in path that returned the perfect file name only.
If we want to see all the functions inside a module then :
const a = require("path");
console.log(a);
Output
C:\Users\jinoy\OneDrive\Desktop\MERN>node script.js
<ref *1> {
resolve: [Function: resolve],
normalize: [Function: normalize],
isAbsolute: [Function: isAbsolute],
join: [Function: join],
relative: [Function: relative],
toNamespacedPath: [Function: toNamespacedPath],
dirname: [Function: dirname],
basename: [Function: basename],
extname: [Function: extname],
format: [Function: bound _format],
parse: [Function: parse],
sep: '\\',
delimiter: ';',
win32: [Circular *1],
posix: <ref *2> {
resolve: [Function: resolve],
normalize: [Function: normalize],
isAbsolute: [Function: isAbsolute],
join: [Function: join],
relative: [Function: relative],
toNamespacedPath: [Function: toNamespacedPath],
dirname: [Function: dirname],
basename: [Function: basename],
extname: [Function: extname],
format: [Function: bound _format],
parse: [Function: parse],
sep: '/',
delimiter: ':',
win32: [Circular *1],
posix: [Circular *2],
_makeLong: [Function: toNamespacedPath]
},
_makeLong: [Function: toNamespacedPath]
}
We can use events module to trigger event and what occur when an event is occurred.
const EventEmitter = require("events");
const emitter = new EventEmitter();
// ^ since EventEmitter is a class
emitter.on("message",(data) => {
console.log(data.text);
});
emitter.on("logout",(data) => {
console.log(data.text);
});
// ^ these are what occour when event is occurred
emitter.emit("message",{text: "user logged"});
emitter.emit("message",{text: "jinoy varghese"});
emitter.emit("logout",{text: "logged out"});
// ^ these are events
In above example, emmitter.emmit() will pass the data to the emitter.on() method. "message" parameter on emitter.emit() will trigger emitter.on() method which has the parameter "message".
Output
C:\Users\jinoy\OneDrive\Desktop\MERN>node script
user logged
jinoy varghese
logged out
To display a simple text or response on website/localhost, we need to import the http module :
const http = require("http");
http.createServer((req,res) => {
res.write("Hello World");
res.end();
}).listen(8080, () => console.log("Server is running"));
The function here after the port number will be executed if the server is created successfully. Don't forget to end the response ( res.end(); ) , if you forget it then the browser will be only in loading state. You can check the response in browser by typing localhost:8080 (you can change the port number to any as you wish).
Output
C:\Users\jinoy\OneDrive\Desktop\MERN>node script
Server is running
Here we are always stopping the running server and retyping the command node script in terminal. But we can use nodemon for catching the changes automatically i.e, we did not need to re-execute the command for each change in the program. If we change any file or line the the server will automatically restart to reflect the new change.
How to install nodemon ?
To install nodemon just type npm i nodemon and hit enter.
We can see that there are new packages and folders created in our current folder like package-lock.json and node_modules.
We don't need to send or trasfer the node_modules folder when we share this project to anyone or host. Because when the new user type npm install, then the packages or modules or dependencies are automatically get installed on the new system.
If we want to update ever packages in a node module with node version, just type npm update and hit enter on terminal. If we want tp downgrade the updates or npm version then type npm install nodemon@2.0.4 (here 2.0.4 is the required version, you can also type any version like 2.0.1 etc) If we type npm install nodemon@latest , it will install the latest version of the nodemon. If you need to check that any version is outdated then type npm outdated .
configuring package.json
After installing the nodemon we need to change the package.json file. The following is the default package.json file.
{
"name": "MERN",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"nodemon": "^2.0.12"
}
}
Now we are going to change the scripts as follows :
{
"name": "MERN",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start":"node script",
"dev":"nodemon script"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"nodemon": "^2.0.12"
}
}
Here we can type any string instead of dev. From now onwards we are typing npm run dev for starting the server. Now if we change anything from any file in the folder, then the server will restart automatically.
How to display an html page with node js
Now if we need to create a html page and diplay it in browser, then follow the following steps:
1. Create a new folder called views.
2. Create a folder index.html inside views.
3. Write your html code inside the index.html page.
4.Change the script.js file as follows.
const http = require("http");
const fs=require("fs");
const path = require("path");
const server = http.createServer((req,res) => {
fs.readFile(path.join(__dirname,"views","index.html"),"utf8",(err,data) => {
if (err) throw err;
res.end(data); //we can also write as res.write(data); and res.end();
});
});
const PORT = process.env.PORT || 8080;
server.listen(PORT, () => console.log(`Server is running on ${PORT}`));
Here fs is module that can be used to read, write, delete, create or manage files from any folder. We now use readFile() for reading the contents from a file.
Syntax :
fs.readFile( filename, encoding, callback_function )
In above example data holds the lines that it read from the index.html file. Here we created a constant PORT so that it can be deployed on host. process.env.port will get the actual port number of our host and if it didn't get the port from the host then the default port (here 8080) will be used.
We can also type like <h1>Hello World</h1> instead of data, that will be displayed on browser.
Now we are going to chnage the html content according to the url because now we will get same content for any url in the host. For that we can use the if statement as follows :
const http = require("http");
const fs=require("fs");
const path = require("path");
const server = http.createServer((req,res) => {
if(req.url === "/"){
fs.readFile(path.join(__dirname,"views","index.html"),"utf8",(err,data) => {
if (err) throw err;
res.write(data);
res.end();
});
}
if(req.url === "/contact"){
fs.readFile(path.join(__dirname,"views","contact.html"),"utf8",(err,data) => {
if (err) throw err;
res.write(data);
res.end();
});
}
});
const PORT = process.env.PORT || 8080;
server.listen(PORT, () => console.log(`Server is running on ${PORT}`));
Now we get another page or redirect to another page(here contaact.html) when the url is localhost:8080/contact.
Express js : The Game Begins : )
To get started with express, let us install it first :
npm install express
Execute the above command in terminal to install express.js. After install you can find a new package inside dependencies in package.json file.
Now we need to uninstall nodemon because nodemon is used only for restarting the server only on localhost. We don't need the nodemon package if it is deployed on any host, the server will take care it automatically during each file change. To uninstall the nodemon type the following in terminal :
npm uninstall nodemon
After uninstall we can find tha there is only one package inside the dependencies in package.json .
But we need nodemon to test it locally and don't need while deployment. For this purpose we install nodemon as developer dependency. So run the command
npm i nodemon -D
or
npm install --save-dev nodemon
After successful installation we can find another line "devDependencies" that contains nodemon in package.json file. By installing like this you are telling to the node that install and use nodemon locally but don't use it when you deploy. Any package that only need in local server and not using when deployment can be added to devDependencies so can avoid waste plugins while deployment.
Before going to express we need to cover a how to import a file or call a function that is written on another file. For this we need to create another file called utils.js and write a function as folows :
const logger = () => {
return 5*2;
}
module.exports = logger;
Only this function in this file can be accessed if there exist a line module.exports=<function name()>. Now try to call the function in script.js by writing as follows :
const func = require("./utils");
console.log(func());
If you want to pass more than one function or to send variable then use as follows :
script.js
const func = require("./utils");
console.log(func);
utils.js
const logger = () => {
return 5*2;
}
const myName = "Jinoy";
module.exports = {
loggerFn: logger,
myNameVar: myName,
};
If you only want to print the variable name which is received, then change script.js as follows:
const func = require("./utils");
console.log(func.myNameVar);
We can also take the values or functions like this :
script.js
const { logger, myName } = require("./utils");
console.log(logger());
console.log(myName);
utils.js
const logger = () => {
return 5*2;
}
const myName = "Jinoy";
module.exports = {
logger,
myName,
};
Now we are going to begin the actual express.js
Actually express is a framework for node js like codeigniter for php.
To display a html in a page, then just use the following code in script.js :
const express = require("express");
const app = express(); //since express is a method
app.get("/", (req,res) => {
res.send("<h1>Hello World</h1>");
});
const PORT = process.env.PORT || 8080;
app.listen(PORT)
To use multiple links, you can use multiple get methods as follows :
const express = require("express");
const app = express(); //since express is a method
app.get("/", (req,res) => {
res.send("<h1>Hello World</h1>");
});
app.get("/contact", (req,res) => {
res.send("<h1>Contact</h1>");
});
const PORT = process.env.PORT || 8080;
app.listen(PORT)
If you need to set 404 then add the following line of code :
app.get("*", (req,res) => {
res.status(404).send("<h1>404</h1>");
});
Similarly we can add use html file to display as a webpage as follows :
const express = require("express");
const app = express(); //since express is a method
const path=require("path");
app.get("/", (req,res) => {
res.sendFile(path.join(__dirname,"views","index.html"));
});
app.get("/contact", (req,res) => {
res.send("<h1>Contact</h1>");
});
app.get("*", (req,res) => {
res.status(404).send("<h1>404</h1>");
});
const PORT = process.env.PORT || 8080;
app.listen(PORT)
You can avoid many app.get() conditions and can use a simple static function :
const express = require("express");
const app = express(); //since express is a method
const path=require("path");
app.use(express.static("views"));
app.get("*", (req,res) => {
res.status(404).send("<h1>404</h1>");
});
const PORT = process.env.PORT || 8080;
app.listen(PORT)
In the above example we can call each file in views by :
http://localhost:8080/contact.html
http://localhost:8080/index.html
http://localhost:8080/
But can call it only if they reside under a single folder.
Creating Token
Let us create a middleware in script.js
const express = require("express");
const app = express(); //since express is a method
const path=require("path");
app.get("/", Token,(req,res) => {
console.log("user logged");
res.send("<h1>success</h1>");
});
function Token(req,res,next)
{
console.log("creating token");
next();
}
const PORT = process.env.PORT || 8080;
app.listen(PORT)
If we didn't use next(), then the message user logged and <h1>success</h1> will never be executed.
We can check wether token is available using the if condition.
const express = require("express");
const app = express(); //since express is a method
const path=require("path");
app.get("/", Token,Validation,(req,res) => {
console.log("user logged");
res.send("<h1>success</h1>");
});
function Token(req,res,next)
{
console.log("creating token");
setInterval(()=>{
const TOKEN = "123";
req.token=TOKEN;
next();
},2000);
}
function Validation(req,res,next)
{
if (req.token){
console.log("Token approved");
next();
}
}
const PORT = process.env.PORT || 8080;
app.listen(PORT)
Output
[nodemon] restarting due to changes...
[nodemon] starting `node script.js`
creating token
Token approved
user logged
We cannot use two or more res.send() to send data to the same page.
We can set not token available response also with if else aas follows :
const express = require("express");
const app = express(); //since express is a method
const path=require("path");
app.get("/", Token,Validation,(req,res) => {
console.log("user logged");
res.send("<h1>success</h1>");
});
function Token(req,res,next)
{
console.log("creating token");
req.token=true;
next();
}
function Validation(req,res,next)
{
if (req.token){
console.log("Token approved");
next();
}
else{
console.log("No Token");
res.send("<h1>no token available</h1>");
}
}
const PORT = process.env.PORT || 8080;
app.listen(PORT)
We can avoid else statement by using return statement inside the function. The return statement will ignore all the lines of code below that.
In advanced form we can use multiple pages inside a script.js with functions containing middleware or functions which have no middleware like home as follows.
const express = require("express");
const app = express(); //since express is a method
const path=require("path");
app.get("/login", Token,Validation,(req,res) => {
console.log("user logged");
res.send("<h1>success</h1>");
});
app.get("/",(req,res) => {
console.log("Home");
res.send("<h1>Home</h1>");
});
function Token(req,res,next)
{
console.log("creating token");
req.token=true;
next();
}
function Validation(req,res,next)
{
if (req.token){
console.log("Token approved");
next();
return;
}
console.log("No Token");
res.send("<h1>no token available</h1>");
}
const PORT = process.env.PORT || 8080;
app.listen(PORT)
We can create default middleware that will be called automatically for every pages as follows:
const express = require("express");
const app = express(); //since express is a method
const path=require("path");
app.use(DateGeneration);
app.get("/login", Token,Validation,(req,res) => {
console.log("user logged");
res.send("<h1>success</h1>");
});
app.get("/",(req,res) => {
console.log("Home");
res.send("<h1>Home</h1>");
});
function Token(req,res,next)
{
console.log("creating token");
req.token=true;
next();
}
function Validation(req,res,next)
{
if (req.token){
console.log("Token approved");
next();
return;
}
console.log("No Token");
res.send("<h1>no token available</h1>");
}
function DateGeneration(req,res,next) {
console.log(new Date());
next();
}
const PORT = process.env.PORT || 8080;
app.listen(PORT)
Here the DateGeneration function is called automatically on every pages.
Note : app.use(DateGeneration); must be called at the top of the script ( before using any app.get() ). If it is written after app.get(), then app.use(DateGeneration); will be ignored.
Capitalize first letter of each word Java
ReplyDeleteRemove duplicate elements from array in Java
Area of circle program in Java
Java program to find area of triangle
Electricity bill program in Java
Matrix multiplication in Java
Java program to find area of rectangle
Number pattern programs in Java
Star pattern programs in Java