Uploaded by tiniumoh

Nodejs 240722

advertisement
Modern JavaScript
JavaScript is a dynamic and lightweight computer programming language which is widely used on
both client-side and server-side development. At first, it was introduced as a scripting language for
web development in early 90s by Netscape company. As you already know JavaScript is wellknown for the development of web pages, until “node.js” introduced in 2009. With the help of
“node.js”, we can use JavaScript outside of the web browsers. As a result, it gained a huge
popularity among back-end developers, and for several years, JavaScript has been recognized as
the most used programming language in the world.
As a beginning let’s dig into the Javascript world from variables.
Variable are used to store the data value that can be changed later on. There are three ways to
declare a variable in Javascript. Which are,
1. Using keyword “var”
2. Using keyword “let”
3. Using keyword “const”
Following program shows the simple program which declares a variable Using “var” keyword
Output of the above code is shown below.
However, if we change the “var” to “let” keyword code will give an error. It’s because when we
declare a variable with “let” keyword it will do two things.
1. It will limit the access to the variable scope which means only inside { } block.
2. It will stop being redeclaration.
In the above code, “let” keyword limit the variable scope inside { } block. Hence it will issue the
following error.
If we change the variable to “const” it will issue the same error as in “let” keyword. But this time
for a different reason.
Marking variable “const” makes that variable constant which means it can be only initialized at
one time. If we try to change it again it will give an error. That is the reason for the error at this
time.
Code
Output
Syntax Error: Missing initializer in const declaration.
However, if we apply “const” to an array/object we still can be able to modify the array/object. But
we can’t assign it to a whole new array or object. An example is shown below.
In Javascript, another important topic is functions.
A function is a group of reusable codes that can be called anywhere in your program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes. Functions allow a programmer to divide a big program into a number of small and
manageable functions.
We can defined function in three different ways.
1. function functionName (parameter) {
//code
}
2. const functionName=(parameter)=>{
// code
}
3. const functionName = (parameter) => //code;
All of these three functions behave the same way.
Now let’s focus on the Arrow functions. The arrow function is one of the features introduced in the
ES6 version of JavaScript. It allows you to create functions in a cleaner way compared to regular
functions.
The syntax of the arrow function is:
let myFunction = (arg1, arg2, ...argN) => {statement(s)}
Example code is shown below.
var show = (a,b,c) => {console.log(a + “ “ + b + “ “ + c );}show(100,200,300);
And another question is What are difference of arrow function and normal function?
Main differences are,
· Unlike regular functions, arrow functions do not have their own this.
· Arguments objects are not available in arrow functions but are available in regular functions.
· Regular functions created using function declarations or expressions are ‘constructible’ and
‘callable’. Since regular functions are constructible, they can be called using the ‘new’ keyword.
However, the arrow functions are only ‘callable’ and not constructible. Thus, we will get a run-time
error on trying to construct a non-constructible arrow function using the new keyword.
How to modern JavaScript handle the object
According to the above code segment, the object is the vehicle. Variable and function declarations
look like this. The key in the code above is [status]. The term for that is a dynamic property. It
implies that if the key value is dynamic, we can specify a placeholder as the key in the object.
when we change the vale status(2 lines) to “order . Then output prints like “order ready”.
freeze method in JS
Among the Object constructor methods, there is a method Object.freeze() which is used to freeze
an object. Freezing an object does not allow new properties to be added to an object and prevents
from removing or altering the existing properties. Object.freeze() preserves the enumerability,
configurability, writability and the prototype of the object. It returns the passed object and does
not create a frozen copy.
However, If you call the freeze ,It freeze only 1 st level value,it doesn’t freeze 2 nd level objects.
Let’s move to the example
In her ename is not changed. But value is change.
1 st level values are changed using freeze. It doesn’t freeze inner-level object values.
Destructuring in JavaScript
Destructuring Assignment is a JavaScript expression that allows to unpack values from arrays,
or properties from objects, into distinct variables data can be extracted from arrays, objects,
nested objects and assigning to variables. In Destructuring Assignment on the left-hand side
defined that which value should be unpacked from the sourced variable.
To take values from an array or properties from JavaScript objects, use the JS expression as shown
below,
1st way -Reducing line numbers.
2nd and 3rd lines are equal to 5th line of above code. Using this way , you can reduce the line
numbers of the code.
2 nd way
with function
considering above code, square object is made (line 2-line8). In here I don’t want to entire area for
calculating area. Only I want base. Therefore, you can make a function to get base. I call the
function using square (line 12). Then pass the square ,Base is only come inside the function and
return the value.
Output is
3 rd way-round off the value
It is an extension of the 2 nd way.
Consider the above code, in this way base and round is used. This method can be used to round to
area value. It gets a value like 148.840 (3 decimal places). Because the round value is 3.
4th way
The above code is shown a normal way to write a file and write a file with destruct.
5th way-with array
code and output
In here 10 is assign to moth1 and rest of the members are assign to other month like new array.
New array output is like {20,30,40,50]
Do you know merge array in JS. Let’s see
Now you can know special kind of scenario. Let’s see below
Consider the data object in the code above. Vehicle, game, and person are equivalent to data on
line 9. Here, game property comes from data and is assigned to the game (line 9), whereas vehicle
property comes from data and is assigned to the vehicle. Additionally, the remaining attributes are
all assigned to people. You may see that a person has a name, city, and age if you record the person
object (output code is shown). There are no game or automobile objects.
Template
Template literals (template strings) allow you to use strings or embedded expressions in the form
of a string. They are enclosed in backticks ``. For example,
const name = 'Jack';console.log(`Hello ${name}!`); // Hello Jack!
Classes in JS
A class is a blueprint for the object. You can create an object from the class.
You can think of the class as a sketch (prototype) of a house. It contains all the details about the
floors, doors, windows, etc. Based on these descriptions, you build the house. House is the object.
Since many houses can be made from the same description, we can create many objects from a
class.
Let’s now examine how classes function in JavaScript using the below code segment.
Once we examine the above code we can see in Javascript Constructors are defined using the
keyword “constructor”.
The output of the above code is shown below.
The first two lines of output are what I would have expected since I called those functions from
each class. However, after the overriding, the output will read “This function is overridden.”
Therefore, despite the fact that this looks exactly like a Java class, it mimics.
Promise in JS
Promises are used to handle asynchronous operations in JavaScript. They are easy to manage
when dealing with multiple asynchronous operations where callbacks can create callback hell
leading to unmanageable code. we can use it to produce synchronous results from asynchronous
processes.
There are 3 states in the promise
1. pending
2. resolved
3. rejected.
Let's consider the following code,
With the aid of a constructor, it can promise. To reproduce the HTTP response, I set the timeout
(it takes some time to populate). The promise’s fundamental mechanism is described in this code.
The promise must be utilized by then() resolving it and catch rejecting it ().
and after 1265 milliseconds, if you execute this, you will see the output displayed below.
Additionally, as seen by the following code, we may create a function that makes use of the
preceding promise. (By using async and await)
This functions with promises and streamlines the promise-writing process. A function that starts
with the async keyword will return a promise. The await keyword is only valid for async functions.
This keyword instructed the JS to wait until the promise yielded results. If you use await without
async, you will get a syntaxError that says, “await is only valid in an async function.” This syntax is
especially easier to understand than promised. then (). Let’s examine the illustrations.
This is what the function will look like with async and await. This is easy to understand compared
to other types.
There are other modern modifications of javaScript.
References
[1]Krish Dinesh, Youtube.com, 2022. [Online].
Available: https://www.youtube.com/watch?v=Jc2iW4yVv38&t=606s. [Accessed: 15- Jul- 2022].
[2]Krish Dinesh, Youtube.com, 2022. [Online].
Available: https://www.youtube.com/watch?v=XK_lB5-XzhQ&t=1232s. [Accessed: 15-
How to use Decorators in JavaScript
What are decorators?
Essentially, the decorator is a design pattern that allows behaviour to be added to an individual
object, either statically or dynamically, without modifying the underlying piece of code.
You may also have heard of this concept as functional composition or higher-order functions.
Therefore, we can achieve it in plain JavaScript for numerous use-cases by calling on one function
to wrap another:
The code above assigns a new function to the variable wrapped that can be called exactly the same
way as the printName function, and will do exactly the same thing. The difference is that it will do
some logging before and after the wrapped function is called:
Decorators in JavaScript and how to use them
Decorators are not a standard JavaScript feature. They are in stage 3 of the ECMA
TC39 specification phase. To use JavaScript Decorators we need to set up a transpiler tool in our
development environment, like Babel.
In JavaScript, we can apply decorators to class fields, methods, and the entire class. Therefore, we
can’t use decorators on plain objects. They only work with classes.
Decorators use a special syntax where they are prefixed with a @ symbol and placed before the code
being decorated.
Let’s look at how we can decorate class properties, class methods and entire classes.
Decorating class fields
In the example below, we can see how to use the decorator syntax on a class field:
In the code above, we have a decorator function called locked that we apply to the password class
field. It takes in three parameters: target, key, and descriptor. The target is the object or function
that is being decorated and the key refers to the property name on that target. The descriptor
contains all of the properties of the target, including those that are being decorated.
Class field decorators work by returning a new descriptor. So we return a new descriptor object
with all of the properties and values from the original except the writable flag set to false. This
prevents changing the password field after it's been instantiated.
Now, if we try changing our password field:
As we can see, attempting to change the password field causes an error because now it's a readonly property.
Decorating class methods
Let’s take a look at an example of using a decorator on a method:
The decorated method takes a descriptor and returns an object that contains the original method
plus any additional logic.
In this example, we are adding some error handling to our getData method. If anything goes wrong
with our request, it will be caught and logged to the console.
Decorating a class
Below we can see how to apply a decorator to the entire class:
The @storeInCache decorator is applied to our class, and it will automatically store any new
instances of User in a cache map.
Conclusion
JavaScript decorators are a powerful feature that provides a good way of writing simple helper
code that can be applied to a lot of places in a very clean and easy-to-read manner, which saves
you time and reduces redundancy in your code. Take advantage of it if you are working with
classes, and remember it is in the stage 3 proposal of TC39.
NodeJS vs Golang: Which one to choose for your next
project?
Building a web or mobile app gets challenging for companies and developers when it comes to
choosing the right tech stack.
As there are a variety of programming languages available to pick from, it gets harder for
developers to choose the most suitable one for the project. Though the list is lengthy and the
languages vary widely, making it is difficult to choose the best option for your individual situation.
In this blog, we’ll compare NodeJS vs Golang to help you decide which language is ideal for your
project. But first, let’s get the basics straight before we begin our comparison.
What is NodeJS?
NodeJS is an open-source JavaScript runtime environment created for the server-side
development of both complex and simple scalable network applications. NodeJS runs on various
operating systems such as Windows, Linux, and macOS.
The foundation of NodeJS is Chrome’s V8 JavaScript engine, which parses and executes
JavaScript code in a Chrome engine in the background. For creating and delivering scalable
server-side applications, rich libraries are there in NodeJS.
What is Golang?
Golang was released in 2009, the same year as NodeJS. The engineers at Google created Golang,
commonly known as Go, which is open-source, statistically typed, multipurpose, cross-platform,
compiled, and quick programming language to solve certain problems by combining the strengths
and eliminating the shortcomings of existing programming languages.
In terms of speed and syntax, the high-efficiency programming language Go is comparable to the C
programming language.
Because Golang is so well-liked by web developers, some may view it as the perfect savior for the
industry. But NodeJS is equally as good. Both are great options based on individual preferences,
albeit they are in a close race. Let’s examine a couple of the areas where the two technologies vary
more closely in order to end the long-lasting debate.
NodeJS vs Golang: Comparison
Performance
Golang has a little advantage over NodeJS in terms of performance and raw speed. Golang is
directly assembled into the machine code and doesn’t need an interpreter. As a result, Golang
performs at a level comparable to that of low-level languages like C++. Golang is just as effective as
NodeJS at IO operations.
Performance-wise, Golang slightly outperforms NodeJS. The optimized and improved singlethreaded NodeJS enhances the efficiency and the V8 JavaScript engine makes sure that the
application runs without any assistance or requirement of an interpreter.
Conclusion- In terms of performance, Golang and NodeJS are on par.
Learning Curve
The learning curve for NodeJS is often less because JavaScript is already widely used. This makes
learning NodeJS for programmers easier than the Go language.
Full-stack developers must understand everything there is to know about a full-stack framework in
Go, including its particular processes, ideas, rules, pointers, strict typing, interfaces, goroutines,
database connections, and many other things.
For your web app project, this means that if you employ a Golang application developer, you or a
member of your team must also be familiar with Golang.
You’ll probably need to hire frontend developers separately because Golang is only for backend
development.
Conclusion- Compared to Golang, NodeJS is significantly easier to learn.
Scalability and Concurrency
In terms of scalability, Google intended to create a programming language for creating robust and
complex enterprise-scale, production-ready applications. Scalability was their major priority,
which they succeeded in achieving.
Go uses goroutines, which enable dependable and simple thread execution that may be done
concurrently and smoothly. Go is the ideal scalable programming language because of these
goroutines.
Go uses concurrency to process more than a thousand requests per second. Go is more scalable
and concurrent than NodeJS just because of this feature. It’s also important to remember that
NodeJS is an asynchronous single-threaded JavaScript engine.
CPU-bound processes can occasionally stop the event loop in NodeJS’ single-threaded design and
make your program run slowly. You end up with a slow app and annoyed users as a result.
Conclusion- Go clearly wins over NodeJS in terms of Scalability and concurrency.
Error Handling
NodeJS uses the traditional throw-catch error handling approach, which is well-liked by
programmers. With this traditional method, errors are promptly displayed and fixed before
moving on to the next step. Many web developers prefer NodeJS over Golang when comparing the
two languages’ error handling because they are more accustomed to Node’s throw-catch
methodology.
On the other hand, Golang performs independent runtime and compilation error checks. While
runtime problems require specific management, compile-time errors are typically connected to
syntax and can be fixed in the code. You must manually examine this function’s return value.
Studies are now being conducted to improve handling procedures in the upcoming Golang version.
Conclusion- In this case, NodeJS and Golang are comparable. This is a TIE.
Development Tools
Go has fewer libraries and packages than NodeJS in terms of development tools. Because of this,
the developer of Go applications still needs to perform a significant amount of manual setup work,
requiring thorough research.
A large community for NodeJS has created multiple libraries and packages for programmers. This
large community also offers additional assistance on websites like Stackoverflow, which boosts
productivity when developing a product.
Conclusion- When comparing developer tools, NodeJS handily wins.
NodeJS vs Go: Which companies are using them?
Companies are using cutting-edge technologies to produce the highest quality and super-fast
performance to thrive in the quickly evolving business environment. Let’s see the companies that
use NodeJS vs Golang.
NodeJS
•
Uber
•
BBC
•
Google
•
Medium
•
Intel
Go
•
LinkedIn
•
Netflix
•
eBay
•
Trello
•
PayPal
Closing notes:
Having thoroughly compared NodeJS and Golang, it is difficult to choose a winner because both
have pros and cons. Therefore, when it comes to NodeJS vs Golang, your choice will depend
exclusively on the project in question.
If you want to know more about the comparison of these two and find out how your business can
benefit from NodeJS development services or Golang development services, get in touch with us
now!
For our latest tech updates visit on OnGraph’s blog.
7 Tricks You Need To Know About Javascript Arrays
It will make your life easier!
Photo by Kelly Sikkema
Javascript has a number of native array functions that are very useful. Of course, there are your
standard pop(), shift(), unshift(), and that entire group of functions. Today, we’re going over some
more functions and tools that you may have never heard of and ways we can use these functions to
achieve cool things.
Copying An Array
These are two different ways you can copy and clone an array.
Initializing Multiple Variables at Once
This is called destructuring.
In the first line, we are not creating an array. Instead, we are assigning each variable with a value.
It would be equivalent to:
let a = 1;
let b = 2;
let c = 3;
The second line is generally the same. The difference is we are providing an initial/default value to
the variables a,b, and c, in case they aren’t assigned a value. In the second line, each variable a,b,
and c are assigned a value. The values given will replace these initial values.
Again:
let a = 1;
let b = 2;
let c = 3;
The third line is nearly identical to the second line; however, variable b is not going to be assigned
a value. Since the third line provides default/initial values, it will look like this:
let a = 1;
let b = 0;
let c = 3;
Lastly, we have line 4. Line 4 is only assigning two variables — a and c — with values. And these
values will be determined by the positioning in the array. Notice variable a is at index 0 and
variable c is at index 2. This will be equivalent to the following:
let a = 1;
let c = 3;
Flatten An Array
Sometimes, you might come across multi-dimensional arrays:
let array = [1,2,3,[4,5,6],[7,[8,9,[10,11]],12,13]];
And accessing every element may become a difficult task. We can flatten this array to form a
single-dimensional array.
let array = [1,2,3,4,5,6,7,8,9,10,11,12,13];
The flat function will flatten the array, making it a one-dimensional array, and store that flattened
array in a new variable. The flat function will not update the existing array.
Access Arrays From Right to Left
Usually, when we want to access elements of an array, we read arrays from left to right. If we want
the first element, find the element at index 0. Second element? Index 1. Third element? Index 2.
You get the idea.
What if we wanted the last element? or the second-to-last element? Do we have to count all the
elements just to find the index of the element that we want?
In other languages, we would simply do:
array[array.length - n];
We would find the length of the array and subtract n to find the nth-to-last element. In Javascript,
we can also do that. Or we can use the Array At function.
Using negative numbers, we can take elements from right to left. For example, array.at(-1) will
take the very last element.
array.at(-2) will take the second-to-last element of an array. And so on.
You can also use the array.at function to take the element at index n. For example, in the last line
above, array[1] is equivalent to array.at(1).
Empty an Array
Either can be used to empty an array.
Swap Values of Variables
This is a simple way to swap values in a single line of code.
You can also do this, but this requires slightly more effort.
Combining Arrays
This shows two ways we can combine two or more arrays.
In the first method, we use the rest parameter. The rest parameter, for example, converts arrays
from [1,2,3,4,5] to 1,2,3,4,5. Without the rest parameter, arrayAB would look like [[1,2,3,4],[5,6,7]]
which we do not want. Using this method, we can combine as many arrays as we want.
In the second method, we are using the concat function. The concat function has the format:
firstArray.concat(secondArray);
Essentially, we are adding the second array to the first array — in that order. But what if we
wanted to concat multiple arrays? That is what the fourth line indicates. It uses the rest parameter
to convert all the arrays into a single array.
Building Web API using Express.js
Summary
In this post, I will show you how to build a blog web API in Node.JS. This tutorial uses Express.JS
for handling HTTP requests and Mongodb for storing data.
Table of Contents
•
Introduction
•
Setup
•
Packages
•
Database
•
MVC Structure
•
Express Application
•
Complete Example
•
Conclusion
Introduction
Node.JS is a platform used for building server side applications using Javascript. With Node.JS,
developers are able to build backend APIs in minutes. It has a great community and a huge set of
packages. These packages help the developers for building great applications. Developers does not
require to build everything from scratch. We mainly focus on two packages. First is Express.JS,
which is one of the most used packages by developers to build web APIs. Second is mongoose,
which is used to simplify the communication between Node.JS and MongoDB.
Requirements
•
Basic Javascript Knowledge
•
Node.JS 10.0.0 or higher
•
NPM 4.6.1 or higher
•
Mongodb 4.2.1 or higher
•
VS-Code or any other editor
Setup
A typical Node.JS application has a root directory which contains at least two
files package.json (holds metadata about the application and required npm packages),
and index.js file (a javascript entry file).
1. Create the directory of the project
mkdir blog-server
cd blog-server
2. Create package.json file
npm init -y
3. Create index.js file (entry file)
// index.js
const PORT = 3000;console.log(`A node.js server that runs on ${PORT}`);
4. Run the application
node index.js
Packages
Our express.js web application requires these packages.
•
express: routing and middleware web framework
•
cors: enables CORS (cross-origin resource sharing)
•
body-parser: parses json body into javascript object
•
morgan: log http requests, important for seeing the request
•
mongoose: mongodb ORM
•
nodemon: eases development by restarting the server on any change
NOTE: nodemon is used as a dev-dependency because it is required only during the development
time.
1. Install packages from NPM.
npm install --save-dev nodemon
npm install --save express cors body-parser morgan mongoose
2. Import packages using require inside index.js file.
const express = require("express");const cors = require("cors");const bodyParser =
require("body-parser");const morgan = require("morgan");const mongoose = require("mongoose");
Database
As mentioned above, we are using Mongodb for storing application related information. We
use mongoose as object mapper between Mongodb and node.js application models.
1. Connect to mongodb
mongoose.connect("mongodb://localhost:27017/blog");
2. Create mongoose schema to define the structure of the document that is read
from or write to Mongodb.
Create a schema named postSchema to define the structure of posts, which it
has title and body.
const postSchema = new mongoose.Schema(
{
title: { type: String, required: true },
body: { type: String, required: true },
},
{ timestamps: true }
);
MVC Like Application
An MVC app is structured into three layers [models, views, controllers]. Sometimes, extra layers
are added to MVC such as DAL, Services, Repositories.
In this example, the app is divided into three layers [models → services →controllers]. Usually,
each layer exists in a directory.
Models
Models represent domain specific data. The model is based on postSchema defined above.
1. create a Post model.
const Post = mongoose.model("post", postSchema);
Services
Service layer is an additional layer in MVC that mediates communication between
a Controller and a Model. This layer adds more abstractions and ease of testability.
1. create a postService entity which exposes two services:
•
find: to query all post data
•
save: to save a post
const postService = {
find: () => Post.find({}),
save: async (postData) => {
const post = new Post({ ...postData });
await post.save();
return post;
},};
Controllers
Controllers as the name implies, controls the incoming request, catches errors and sends back a
response to the client.
1. create a postController which it has two actions:
•
find: handles GET /api/posts
•
save: handles POST /api/posts
const postController = {
find: async (req, res, next) => {
try {
const posts = await postService.find({ ...req.query });
res.json(posts);
} catch (error) {
error.msg = "failed to retrieve posts";
next(error);
}
},
save: async (req, res, next) => {
try {
const post = await postService.save(req.body);
res.json(post);
} catch (error) {
error.msg = "failed to create post";
next(error);
}
},
};
Express Application
Express is a routing and middleware web framework that has minimal functionality of
its own: An Express application is essentially a series of middleware function calls.
1. create an express application
const app = express();
Middlewares
Middlewares are functions executed before or after the controller actions.
app.use(cors());
app.use(morgan("tiny"));
app.use(bodyParser.json());
Express Router
The express router route the request to a specific action in the controller.
1. define two routes based on Express Router to handle
•
GET /api/posts
•
POST /api/posts
const router = express.Router();
router.get("/posts", postController.find);
router.post("/posts", postController.save);
app.use("/api", router);
Complete Example
I have included a complete express server example.
/** STEP
1:
Packages
*/
// For a minimal node.js server we need to install and import the bellow packages
const express = require("express"); // fast, open-source node.js server
const cors = require("cors"); // enables CORS (cross-origin resource sharing)
const bodyParser = require("body-parser"); // parses json body into javascript object
const morgan = require("morgan"); // log http requests
const mongoose = require("mongoose"); // mongodb orm
/** STEP 2: DATABASE */
// connect to mongodb
mongoose.connect("mongodb://localhost:27017/blog", {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
});
// create mongoose schema
const postSchema = new mongoose.Schema(
{
title: { type: String, required: true },
body: { type: String, required: true },
},
{ timestamps: true }
);
/** STEP 3: MVC Like App */
// An MVC app is structured into [Models, Views, Controllers]
// A typical API does not to expose views.
// Sometimes, extra layers are added to MVC such as DAL, Services, Repositories
// In this example, the app is divided into 3 layers [Models -> Services -> Controllers]
// Note: usually, each layer exists in a directory.
// MODELS: represents domain-specific data
// post model - built based on mongoose schema postSchema [defined above]
const Post = mongoose.model("post", postSchema);
// SERVICES: is an additional layer in MVC that mediates communication between a Controller and a Model
// Note: this layer adds more abstractions and ease of testability
// post service
const postService = {
// find service - uses post model to query all posts
find: () => Post.find({}),
// save service - uses post model to save a post
save: async (postData) => {
const post = new Post({ ...postData });
await post.save();
return post;
},
};
// post controller - each action in the controller, handles a specific route.
const postController = {
// GET /api/posts
find: async (req, res, next) => {
try {
const posts = await postService.find({ ...req.query });
res.json(posts);
} catch (error) {
error.msg = "failed to retrieve posts";
next(error);
}
},
// POST /api/posts
save: async (req, res, next) => {
try {
const post = await postService.save(req.body);
res.json(post);
} catch (error) {
error.msg = "failed to create post";
next(error);
}
},
};
// routes - define the routes based on express Router
const router = express.Router();
router.get("/posts", postController.find); // GET /api/posts
router.post("/posts", postController.save); // POST /api/posts
/** STEP 4: Express Server */
// create an express app
const app = express();
// use third-party middlewares
app.use(cors());
app.use(morgan("tiny"));
app.use(bodyParser.json());
// handle routes
// use the router within the express app to handle routes defined above
app.use("/api", router);
// use custom middlewares if any
// handle a request if url path is not found
const notFound = (req, res, next) => {
res.status(404);
res.json({
status: 404,
error: "not found",
});
};
// handle an error if occured in the controller
const handleError = (error, req, res, next) => {
console.log(error);
res.status(error.status || 500);
res.json({
message: error.message || "failed: not known error",
msg: error.msg,
stack: error.stack,
});
};
app.use(notFound); // in-case a url path is not found
app.use(handleError); // in-case an error has occured
// Run the server
// running the server on a port to listen to HTTP requests.
const PORT = 3000;
app.listen(PORT, (err) => {
if (err) console.log(err);
else console.log(`Server started on port: ${PORT}`);
});
Conclusion
You have learnt in detail, how to create an express server and connect to mongodb for storing data.
You have exposed some APIs. In this tutorial I have written all code in one file for simplicity. You
can visit this repository for the complete example.
Asynchronous And Synchronous In JS
Synchronous:- As the name suggests synchronous means to be the sequence. The tasks were
completed in sequence. If the first task is completed then only one can move on to the second task.
Simply, you can say that code is executed line by line .before going next task you should complete
the previous task.
let us understand with the help of an example:-
https://replit.com/@SCION-OFOF/blogJavaScript#Synchronous%20JavaScript.js
As you can code executed line by line this is Synchronous Programming.
Asynchronous :- In synchronous, the code is executed line by line, there is no problem if the
code execution takes a small time, Synchronous is doing well. On the other hand, if the program is
large and takes little time to execution when Asynchronous come to picture it allows multitasking
that does not await whether the previous one is completed or not.
Simply You Can Say that function runs with parallel other function which is called Asynchronous
.like as setTimeout() Etc. One thing to note is JavaScript is a single-thread language. JavaScript
relies on the call stack to perform asynchronous tasks.
let us understand with help of an example.
As you can see, the above code output should be “Start Mid-Operation End”. The setTimeout
function takes 3 seconds to execute, the JS engine has registered this function in the call stack, it
doesn’t wait for 3 seconds and proceeds to the next line execution. A good example of
Asynchronous.
Asynchronous says that=>I WILL FINISH LATER!
About call stack
Will discuss in the next blog.
Please give your valuable feedback and suggestions.
Thanks.
IIFE(Immediately Invoked Function Expression)
JavaScript
IIFE is a function that runs as soon as it is defined. We can construct the IIFE function by
wrapping it in parentheses and adding a parenthesis at the end of the function. For example :(function() { // Code that runs in your function })()
The function consists of two-part of codes. In the first part, the declaration of function (function
code ) is enclosed by parentheses. In the second part, “()” a grouped parentheses, the JavaScript
engine will interpret the function directly.
Syantax
( function(){
code that runs
})()
In ES6
(()=>{})()
Let us try to understand the IIFE method using the following example:-
Immediately Invoked Function Expression
ES6
Some important info about IIFE
1. That variable declare inside immediately Invoked function expression will be not available
outside the function.
2. IIFE function can be named or anonymous.
3. IIFE is the function able to use parameters.
IIFE with parameters
Please give your valuable feedback and suggestions.
Thanks.
Download