Node.js – AppDividend https://appdividend.com Latest Code Tutorials Thu, 06 Jun 2019 16:35:41 +0000 en-US hourly 1 https://wordpress.org/?v=5.2.1 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Node.js – AppDividend https://appdividend.com 32 32 What is process.env in Node.js | Environment Variables in Node.js https://appdividend.com/2019/06/06/what-is-process-env-in-node-js-environment-variables-in-node-js/ https://appdividend.com/2019/06/06/what-is-process-env-in-node-js-environment-variables-in-node-js/#respond Thu, 06 Jun 2019 16:33:08 +0000 http://localhost/wordpress/?p=8145 What is process.env in Node.js | Environment Variables in Node.js

In this tutorial, we will see What is process.env in Node.js | Environment Variables in Node.js. Working with environment variables is the great way to configure different configurations of your Node.js application. Many cloud hosts like Heroku, Azure, AWS, now.sh, etc. uses node environment variables. Node.js modules are using environment variables. Hosts, for example, will set the PORT variable that […]

The post What is process.env in Node.js | Environment Variables in Node.js appeared first on AppDividend.

]]>
What is process.env in Node.js | Environment Variables in Node.js

In this tutorial, we will see What is process.env in Node.js | Environment Variables in Node.js. Working with environment variables is the great way to configure different configurations of your Node.js application. Many cloud hosts like Heroku, Azure, AWS, now.sh, etc. uses node environment variables. Node.js modules are using environment variables. Hosts, for example, will set the PORT variable that specifies on which port the server should listen to work properly. Modules might have the different behaviors (like logging) depending on the value of the NODE_ENV variable.

What is process.env in Node.js

The Node injects the process.env global variable at runtime in our app to use, and it represents the state of the system environment of our app when it starts. For example, if the system has the PATH variable set, this will be made accessible to you through the process.env.PATH variable which you can use to check where binaries are located and make external calls to them if required.

Why environment variable in Node.js is important

When we write the code, we can never be sure where our app can be deployed. If we require the database in development, we spin up the instance of it, and we link to it via a connection string , something like 127.0.0.1:3306. However, when we deploy it to the server in production, we might need to link it to the remote server, let say 32.22.2.1.

Now, we can write the code of linking the database using the process.env file.

const connection = new Connection(process.env.DB_CONNECTION_STRING);

Specifying an external service dependency allows us to link to the remote load-balancer protected database cluster which can scale independently of an app, and will enable us to have the multiple instances of our app independently of a database service.

Basics of process.env

Accessing environment variables in the Node.js is supported out of the box. When your Node.js process boots up, it will automatically provide an access to all the existing environment variables by creating the env object as a property of the process global object.

I am using Node.js version 11. Now, if you have not installed Node.js, then please install it.

After that, create a folder and inside create a file called app.js and add the following code.

console.log(process.env);

Now, go to the terminal and hit the following command.

What is process.env in Node.js

 

The above code should output all the environment variables that this Node.js process is aware of. If we want to access one specific variable, access it like any property of the object. Let’s access the PORT property.

console.log(process.env.PORT);

You will see the undefined in the output because we have defined a specific port yet.

Cloud hosts like Heroku or Azure; however, use the PORT variable to tell you on which port your server should listen for the routing to work correctly. Therefore, the next time you set up the web server, you should determine the port to listen on by checking PORT first and giving it a default value otherwise.

See the following code.

// app.js

const app = require('http').createServer((req, res) => res.send('Ahoy!'));
const PORT = process.env.PORT || 4000;

app.listen(PORT, () => {
  console.log(`Server is listening on port: ${PORT}`);
});

In the above code, we have created the HTTP server, and that server is running on the either defined port in the .env file or by default 4000.

Run the file and see the output.

Basics of process.env

 

Since the process.env is simply an ordinary object, we can set/override the values very easily.

Explicitly loading variables from the .env file

We have two levels to work, when dealing with a server provisioning: 1) infrastructure and 2) application levels. We can either set an environment through the application-level logic, or we can use the tool to provide an environment for us.

A standard application-level tool is dotenv, which allows us to load the environment variables from a file named .env. We can install it via NPM using the following command.

npm install dotenv --save

Afterward, add the following line to the very top of your entry file.

require('dotenv').config();

The above code will automatically load the .env file in the root of your project and initialize the values. It will skip any variables that already have been set.

You should not use the .env file in your production environment though instead set the values directly on the respective host. Therefore, you might want to wrap the config statement in the if-statement.

if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}

Now, create a file called .env and add the following one line of code inside that .env file. You need to create the .env file in the root of your project folder.

PORT = 3000

Now, write the following code inside the app.js file.

// app.js

if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}

const app = require('http').createServer((req, res) => res.send('Ahoy!'));
const PORT = process.env.PORT || 4000;

app.listen(PORT, () => {
  console.log(`Server is listening on port: ${PORT}`);
});

Now, run the server and you will see the server is running on PORT: 3000 and not on 4000.

While this is a convenient for development needs, it is considered the bad practice to couple the environment with our application, so keep it out by adding .env to your .gitignore file.

At an infrastructure level, we can use the deployment manager tools like PM2, Docker Compose, and Kubernetes to specify an environment.

PM2 uses an ecosystem.yaml file where you can specify the environment using the env property.

apps:
  - script: ./app.js
    name: 'my_application'
    env:
      NODE_ENV: development
    env_production:
      NODE_ENV: production
    ...

Docker Compose likewise allows for the environment property to be specified in the service manifest.

version: "3"
services:
  my_application:
    image: node:8.9.4-alpine
    environment:
      NODE_ENV: production
      ...
    ...

Kubernetes has an equivalent the env property in the pod template manifest which allows us to set the environment:

kind: Deployment
apiVersion: extensions/v1beta1
metadata:
  name: my_application
spec:
  ...
  template:
    spec:
      env:
        - name: NODE_ENV
          value: production
        ...

Using the process.env.* correctly results in applications that can be tested with ease and deployed/scaled elegantly. So, we have seen process.env in Node.js very deeply in this article.

Finally, What is process.env in Node.js | Environment Variables in Node.js is over.

The post What is process.env in Node.js | Environment Variables in Node.js appeared first on AppDividend.

]]>
https://appdividend.com/2019/06/06/what-is-process-env-in-node-js-environment-variables-in-node-js/feed/ 0
Node Express Image Upload and Resize Tutorial Example https://appdividend.com/2019/02/14/node-express-image-upload-and-resize-tutorial-example/ https://appdividend.com/2019/02/14/node-express-image-upload-and-resize-tutorial-example/#comments Thu, 14 Feb 2019 00:19:04 +0000 http://localhost/wordpress/?p=4827 Node Image Upload Resize Tutorial With Example

Node Express Image Upload and Resize Tutorial Example is today’s topic. Node.js as a platform and express as a lightweight framework is the best choice for backend development. We can build Web APIs through this framework very quickly, and it has tremendous support for the NoSQL databases like MongoDB. You can find the tutorial about Node Express […]

The post Node Express Image Upload and Resize Tutorial Example appeared first on AppDividend.

]]>
Node Image Upload Resize Tutorial With Example

Node Express Image Upload and Resize Tutorial Example is today’s topic. Node.js as a platform and express as a lightweight framework is the best choice for backend development. We can build Web APIs through this framework very quickly, and it has tremendous support for the NoSQL databases like MongoDB. You can find the tutorial about Node Express MongoDB tutorial on this blog. In this tutorial, we will upload an image to the Node.js server and resize the image using the sharp library.

Node Express Image Upload and Resize Tutorial

Okay, now let’s start our project.

Step 1: Create Node Express Project

Create a project folder by the following command.

mkdir nodeimageupload
cd nodeimageupload

Now, create a package.json file using the following command.

npm init -y

Next, install express as a framework,ejs as a template engine, body-parser, multer as a  node.js middleware for handling multipart/form-data, uuid for getting the random name, sharp as an image resize libraries using NPM.

npm install express body-parser ejs uuid multer sharp --save

Also, install the nodemon server as a development dependency.

npm install nodemon --save-dev

Now, open the project in Visual Studio Code.

Change the package.json file and add the following line in “scripts” object.

"scripts": {
    "start": "nodemon server.js"
},

Step 2: Create a server.js file.

Create one file in the project root called the server.js and added the following code inside it.

// server.js

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

app.listen(port, function () {
  console.log('Server is running on PORT',port);
});

Now, go to the terminal and start the node server by the following command.

npm start

 

Node Express Image Upload and Resize Tutorial Example

So, our nodemon development server is up and running.

Step 3: Configure the EJS templating engine.

For including the css and js files in the express, first, we will create a static directory called public in the root, and in that, we will put our CSS and JS files. So, create the first public directory.

Add the following code inside the server.js file.

// server.js

app.use(express.static('public'));

Next step is to set the ejs template engine. Add the following code inside the server.js file.

// server.js

app.set('view engine', 'ejs');

We need to create one folder inside our root called views. In that folder make one file called index.ejs.

<!-- index.ejs -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>EJS Engine</title>
  </head>
  <body>
    <p>Node Express Image Upload and Resize Example</p>
  </body>
</html>

Also, create an index.html file inside the public folder.

<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=He, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Node Express Image Upload Example</title>
</head>
<body>
   <p>
     Node Express Image Upload and Resize Example
   </p>
</body>
</html>

Step 4: Configure Express Router.

Set up the routes for our application. So use Router module provided by Express js. So, create a file in the root folder called router.js.

Now, write the following code inside the router.js file.

// router.js

const express = require('express');
const app = express();
const router = express.Router();

router.get('/', async function (req, res) {
  await res.render('index');
});
module.exports = router;

Now in the server.js filewe need to require the router.js file.

// server.js

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = process.env.PORT || 3000;
const router = require('./router');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.use(express.static('public'));
app.set('view engine', 'ejs');

app.use('/upload', router);

app.listen(port, function () {
  console.log('Server is running on PORT',port);
});

Now, go to the browser and hit this URL: http://localhost:3000/upload. You can see the basic HTML view.

Step 5: Create a form.

Inside the index.ejs file, we need to create one HTML form that can upload the image.

// index.ejs

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>EJS Engine</title>
  </head>
  <body>
      <p>Image Upload</p>
      <form method="post" action="upload/post" enctype="multipart/form-data">
        <input type="file" name="image" /><br /><br />
        <button type="submit" name="upload">Upload</button>
      </form>
  </body>
</html>

Now, go to the http://localhost:3000/upload and see the underlying HTML form that can upload an image.

Step 6: Create file upload middleware

Okay, to handle the multipart/form-data in Node.js, we have already installed the multer library. So let’s use that and create a middleware inside the root of the project called uploadMiddleware.js.

// uploadMiddleware.js

const multer = require('multer');

const upload = multer({
  limits: {
    fileSize: 4 * 1024 * 1024,
  }
});

module.exports = upload

Now, import this middleware inside the router.js file where we handle the POST request.

// router.js

const express = require('express');
const app = express();
const router = express.Router();
const upload = require('./uploadMiddleware');

router.get('/', async function (req, res) {
  await res.render('index');
});

router.post('/post', upload.single('image'), async function (req, res) {
  await console.log('post');
});

module.exports = router;

Here, we have used the node async await feature. 

So, when the user tries to upload an image, in the server, the router. Post function will be executed, and in the console, a post will be printed. That means, now we need to resize the image and then save in the file directory.

Step 7: Resize the image

For resizing the image in Node.js and achieve the High-performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP and TIFF images is Sharp. We have already installed the sharp. Now, create a file inside the root called Resize.js and add the following code.

// Resize.js

const sharp = require('sharp');
const uuidv4 = require('uuid/v4');
const path = require('path');

class Resize {
  constructor(folder) {
    this.folder = folder;
  }
  async save(buffer) {
    const filename = Resize.filename();
    const filepath = this.filepath(filename);

    await sharp(buffer)
      .resize(300, 300, {
        fit: sharp.fit.inside,
        withoutEnlargement: true
      })
      .toFile(filepath);
    
    return filename;
  }
  static filename() {
    return `${uuidv4()}.png`;
  }
  filepath(filename) {
    return path.resolve(`${this.folder}/${filename}`)
  }
}
module.exports = Resize;

So, in the above file, we have created a class called Resize.js and accepts one argument which is folder path up to images folder. Now, you need to create the images folder inside the public directory.

Then, we have defined the static function filename which returns the random string of filename and then define the filepath function which returns the complete filepath of that uploaded image.

Then we have defined the save() function, which accepts the file buffer coming from the user request and then resize that image and upload to that filepath and return the filename to the User.

Now, import the Resize.js file inside the router.js file.

Step 8: Save the image in the file system

Now, we need to import the Resize.js file inside the router.js file because we are handling the post request there. Write the following code inside the router.js file.

// router.js

const express = require('express');
const app = express();
const path = require('path');

const router = express.Router();
const upload = require('./uploadMiddleware');
const Resize = require('./Resize');

router.get('/', async function (req, res) {
  await res.render('index');
});

router.post('/post', upload.single('image'), async function (req, res) {
  const imagePath = path.join(__dirname, '/public/images');
  const fileUpload = new Resize(imagePath);
  if (!req.file) {
    res.status(401).json({error: 'Please provide an image'});
  }
  const filename = await fileUpload.save(req.file.buffer);
  return res.status(200).json({ name: filename });
});

module.exports = router;

First, inside the router.post request, we have defined the upload folder and then pass that folder to the constructor of Resize class. It will return the object and then we call the save() method on that object and pass the image buffer as an argument to the save() function and return the file name and we are for now just displaying the filename in JSON format to the User.

If the file is not there then we are displaying an error message to the user in JSON format.

Step 9: Run the Project.

Now, if you try to upload an image, you will see the output in the browser like below image.

 

Upload and Resize the image

So, we have got the correct JSON response. Now, go to the file system and inside the public >> images folder, you can see the randomly named image will be there.

Finally, Node Express Image Upload and Resize Tutorial Example is over. Thanks for taking and also, see the Github code, if you find any error.

Github Code

The post Node Express Image Upload and Resize Tutorial Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/02/14/node-express-image-upload-and-resize-tutorial-example/feed/ 2
Node Streams Tutorial With Example https://appdividend.com/2018/11/28/node-streams-tutorial-with-example/ https://appdividend.com/2018/11/28/node-streams-tutorial-with-example/#respond Wed, 28 Nov 2018 23:46:52 +0000 http://localhost/wordpress/?p=2366 Node Streams Tutorial With Example

Node Streams Tutorial With Example is today’s leading topic. Streams are collections of data just like the arrays or strings. The difference between arrays and streams is that streams might not be available all at once, and they don’t have to fit in the memory. This feature makes streams more powerful when working with the massive amounts […]

The post Node Streams Tutorial With Example appeared first on AppDividend.

]]>
Node Streams Tutorial With Example

Node Streams Tutorial With Example is today’s leading topic. Streams are collections of data just like the arrays or strings. The difference between arrays and streams is that streams might not be available all at once, and they don’t have to fit in the memory. This feature makes streams more powerful when working with the massive amounts of data, or the data that is coming from the external source one chunk at a time. Many of the built-in modules in Node implement the streaming interface. So Stream data are not available at once, but they are available at some point of time in the form of chunk data. That is why it is beneficial for developing a streaming web application like Netflix or Youtube.

If you want to learn more about Node.js then check out this course NodeJS – The Complete Guide (incl. MVC, REST APIs, GraphQL)

Node Streams Tutorial With Example

I am using node.js version v11.3.0, and your version might be v10, but it does not matter here. The Stream is an abstract interface for working with streaming data in the Node.js. The stream module provides the base API that makes it easy to build the objects that implement the stream interface. 

Streams can be readable, writable, or both.  All streams are instances of EventEmitter.

The following statement can access the stream module.

const stream = require('stream');

Why Streams

Streams primarily provide the following advantages.

  • Memory efficiency: You don’t need to carry the massive amounts of data in memory before you can process it.
  • Time efficiency: It takes way less time to start processing the data as soon as you have it, rather than waiting till the whole data payload is available to start the process.

Types of Streams

There are four fundamental stream types in Node.js:

Let us take a basic simple example of filesystem module streams.

Create a project folder using the following command.

mkdir streams

Go inside that folder and create a file called the server.js and add the following code.

// server.js

const http = require('http')
const fs = require('fs')

const server = http.createServer(function (req, res) {
  fs.readFile('data.txt', (err, data) => {
    res.end(data)
  })
})
server.listen(3000, () => {
  console.log('server is running')
})

Here, we have used the http module to create a web server and also imported the module called fs which is the filesystem module for node.js applications.

When the server starts, we are reading the content of the file data.txt and send the response to that data to a client.

So, we can see the output inside the browser.

Save that file and also create one more file inside the root called data.txt and add the following code in it.

// data.txt

node streams
file streams

Go to the terminal and start the node server using the following command.

node server

Switch to the browser and go to this URL: http://localhost:3000/

We can see the content of the data.txt file.

Here, one thing you can note that when the reading of the file is completed then and then it will send a response. So, if the file is very big, then it takes some time to read the whole file and then sending back to the client.

We can overcome this problem by using the Stream. As we have discussed earlier that streams can emit the chunks of data to the client at some time interval. So, as soon as some chunk of data read, it will emit to the client.

We can use the Streams in the above example like this.

// server.js

const http = require('http')
const fs = require('fs')

const server = http.createServer((req, res) => {
  const stream = fs.createReadStream('data.txt')
  stream.pipe(res)
})
server.listen(3000, () => {
  console.log('Node.js stream on port 3000');
});

Instead of waiting until the file is totally read, we can start streaming it to the HTTP client as soon as we have the chunk of data ready to be sent.

#Example 2

Let us take a second example of Node.js Stream. Write the following code inside a server.js file.

// server.js

const fs = require('fs')

let data = ''

const readerStream = fs.createReadStream('data.txt')

readerStream.setEncoding('UTF8')

readerStream.on('data', (chunk) => {
   data += chunk
})

readerStream.on('end',() => {
   console.log(data)
})

readerStream.on('error', (err) => {
   console.log(err.stack)
})

console.log('Node readerStream');

Here, we get the output inside the terminal because we have not used any web server. This example is an instance of a node eventemitter.

  • data − This event is fired when there is data available for read.

  • end − This event is fired when there is no more data to read.
  • error − This event is fired when there is an error receiving or writing data.
  • finish − This event is fired when all the data has been flushed to the underlying system.

Writable Streams

Write the following code inside a server.js file.

// server.js

const fs = require('fs')

const data = 'Writable Stream Example'

const writerStream = fs.createWriteStream('write.txt')

writerStream.write(data,'UTF8')

writerStream.end()

writerStream.on('finish', function() {
   console.log('Writing completed');
})

writerStream.on('error', function(err) {
   console.log(err.stack)
})

console.log('Streaming Ended')

When the server starts, if the file is not there, it will create it and write the data inside it, and then when the writing is over, we can see the output inside the terminal as well as inside the newly created file.

Piping the Streams

Piping is a mechanism where we provide the output of one stream as the input to another stream. It is usually used to get data from one stream and to pass the output of that stream to another stream.

// server.js

const fs = require('fs')

const readerStream = fs.createReadStream('data.txt')

const writerStream = fs.createWriteStream('data2.txt')

readerStream.pipe(writerStream)

console.log('Piping ended')

So, here, we are reading the data from the data.txt file and writing the data to the other file called data2.txt.

We have piped the readerStream to writerStream.

Difference between fs.readFile() and fs.createReadStream()

The fs.readFile() loads file and reads it into memory and then writes it to response whereas fs.createReadStream() sends chunks of file like writing small chunks of file dividing the entire process into that chunk size of file writing which reduces memory load and memory wastage/garbage reduction.

Finally, Node Streams Tutorial With Example is over.

The post Node Streams Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/11/28/node-streams-tutorial-with-example/feed/ 0
How To Use Template Engines With Express https://appdividend.com/2018/11/24/how-to-use-template-engines-with-express/ https://appdividend.com/2018/11/24/how-to-use-template-engines-with-express/#respond Sat, 24 Nov 2018 16:08:23 +0000 http://localhost/wordpress/?p=2324 How To Use Template Engines With Express Tutorial with Example

In this example, we will see How To Use Template Engines With Express.  A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values and transforms the template into an HTML file sent to the client. This approach makes it easier to design […]

The post How To Use Template Engines With Express appeared first on AppDividend.

]]>
How To Use Template Engines With Express Tutorial with Example

In this example, we will see How To Use Template Engines With Express.  A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page. The significant benefit of such approach when it comes to templates is explicitly being able to render HTML on the server side. So, we can do the SEO easily, and we are not rendering the JSON data. In this article, I want to look at some of the most popular JavaScript templating engines.

If you want to learn more about Node.js then check out this course NodeJS – The Complete Guide (incl. MVC, REST APIs, GraphQL)

How To Use Template Engines With Express

Now, first we install the express web framework, and then we start implementing different template engines in our node.js application.

#1: Create Node.js Express server

First, create a node.js project directory.

mkdir exptemplate

Now, go inside the folder and initialize the package.json file.

npm init -y

Next step is to install the express framework.

npm install express --save

Now, create a file inside the root called server.js and add the following code.

// server.js

const app = require('express')();
const PORT = process.env.PORT = 4000;

app.listen(PORT, () => {
  console.log('The server is running on port',PORT);
});

We can use the nodemon server for development. So let us install it using the following command.

npm install nodemon --save

Now, start the server using the following command.

nodemon server

 

How To Use Template Engines With Express

#2: Install and configure Pug templating engine

Okay, now install our First templating engine Pug using the following command.

npm install pug --save

Create one folder inside the root called views.

Now that Pug is installed set it as the templating engine for your app. You don’t need to ‘require’ it. Add the following code to your server.js file.

// server.js

app.set('view engine', 'pug');
app.set('views',path.join(__dirname, 'views'));

Here, we have defined the template engine Pug.

Also, we have defined the directory from which these template files can load in our application.

So, when the request comes from the client, it will go to the router and then router redirect to one of the pages inside the views folder, and then that page will be rendered.

Next step is to create a file inside the views folder called template.pug and add the following code.

// template.pug

doctype html
html
   head
      title Hello From Pug Templating Engine
   body
      p.greetings#peopleHello Hello From Pug Templating Engine!

It is the pug syntax to write the HTML.

To run this page, add the following route to your server.js file.

// server.js

app.get('/template', function(req, res){
  res.render('template');
});

So, our final server.js file looks like below code.

// server.js

const app = require('express')();
const path = require('path');
const PORT = process.env.PORT = 4000;

app.set('view engine', 'pug');
app.set('views',path.join(__dirname, 'views'));

app.get('/template', function(req, res){
  res.render('template');
});

app.listen(PORT, () => {
  console.log('The server is running on port',PORT);
});

Save the file and see the console, if we are running with errors and then if not then make sure your nodemon server is running. If everything looks great, then go to the browser and switch to the following URL.

http://localhost:4000/template

You can see that our HTML is rendering and we have successfully integrated the Pug templating engine.

#3: Install and configure Mustache template

We can use the Mustache templating engine in Express; you first install the mustache-express package.

npm i mustache-express

Now, require and configure the module. I have written the final server.js file for implementing the mustache-express module.

// server.js

const app = require('express')();
const path = require('path');
const PORT = process.env.PORT = 4000;
const mustacheExpress = require('mustache-express');

app.engine('html', mustacheExpress());
app.set('view engine', 'html');
app.set('views',path.join(__dirname, 'views'));

app.get('/template', function(req, res){
  res.render('index.html', {yourdata: 'Hello from Mustache Template'});
});

app.listen(PORT, () => {
  console.log('The server is running on port',PORT);
});

Also, we need to create a file inside the views folder called index.html and write the following HTML code inside the index.html file.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Mustache Template Engine</title>
</head>
<body>
  <div>
    {{ yourdata}}
  </div>
</body>
</html>

Save the file and go to the browser and navigate to the following URL.

http://localhost:4000/template

You can see that we have successfully integrated the Mustache template in Express.

#4: Install and configure EJS template

We can install the EJS(Embedded Javascript) template using the following command.

npm install ejs --save

Now, import the ejs template as well as configure the ejs template.

Write the final code inside the server.js file.

// server.js

const app = require('express')();
const path = require('path');
const PORT = process.env.PORT = 4000;
const ejs = require('ejs');

app.set('view engine', 'ejs');
app.set('views',path.join(__dirname, 'views'));

app.get('/template', function(req, res){
  res.render('welcome.ejs', {yourdata: 'Hello from EJS Template'});
});

app.listen(PORT, () => {
  console.log('The server is running on port',PORT);
});

So, here we have set the template engine to ejs. Now create a file called the welcome.ejs inside the views folder.

<!-- welcome.ejs -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>EJS Template</title>
</head>
<body>
  <%= yourdata %>
</body>
</html>

Save the file and go to the browser and switch to the following URL.

http://localhost:4000/template

Now, we have successfully integrated the EJS template.

Finally, How To Use Template Engines With Express Tutorial with Example is over. Thanks for taking.

 

The post How To Use Template Engines With Express appeared first on AppDividend.

]]>
https://appdividend.com/2018/11/24/how-to-use-template-engines-with-express/feed/ 0
How To Serve Static Files in Express https://appdividend.com/2018/11/24/how-to-serve-static-files-in-express/ https://appdividend.com/2018/11/24/how-to-serve-static-files-in-express/#respond Sat, 24 Nov 2018 10:10:16 +0000 http://localhost/wordpress/?p=2312 Server static files in express

In this tutorial, we will see How To Serve Static Files in Express. Express is the Fast, unopinionated, minimalist web framework for Node.js. We can also build the robust api using HTTP utility methods and middleware at your disposal. Express provides the thin layer of web application features, without obscuring Node.js features that you know and love. Right now Express […]

The post How To Serve Static Files in Express appeared first on AppDividend.

]]>
Server static files in express

In this tutorial, we will see How To Serve Static Files in Express. Express is the Fast, unopinionated, minimalist web framework for Node.js. We can also build the robust api using HTTP utility methods and middleware at your disposal. Express provides the thin layer of web application features, without obscuring Node.js features that you know and love. Right now Express Framework’s version is 4.16.0.

If you want to learn more about Node.js then check out this course NodeJS – The Complete Guide (incl. MVC, REST APIs, GraphQL)

How To Serve Static Files in Express

We can serve the static files such as images, CSS, and JavaScript files using the express.static built-in middleware function in Express. The syntax is following.

express.static(root, [options])

The root argument specifies a root directory from which to serve the static assets. The function determines the file to serve by combining the req.url with the provided a root directory. When the file is not found, instead of sending a 404 response, it instead calls next() to move on to a next middleware, allowing for stacking and fall-backs. Now, let us take an example to serve static files in express.

#1: Install Express and create a server

Create a project folder.

mkdir expstatic

Now, initialize the package.json file using the following command.

npm init -y

Install express using the following command.

npm install express --save

Now, create a folder inside the root called public.

Also, create one file inside the root called server.js.

// server.js

const express = require('express');

const app = express();
const PORT = process.env.PORT = 4000;

app.listen(PORT, () => {
  console.log('Server is running at:',PORT);
});
Go to the terminal and start the server.
node server

 

How To Serve Static Files in Express

#2: Add Static Middleware

First, we need to define the root directory that can act as a folder, from which we can load the static assets like CSS, JS, and Images.

In our case, it is the public directory. So let us define it.

// server.js

app.use(express.static('public'));

So, our server.js file looks like this.

// server.js

const express = require('express');

const app = express();
const PORT = process.env.PORT = 4000;

app.use(express.static('public'));

app.listen(PORT, () => {
  console.log('Server is running at:',PORT);
});

Now, our static files’ folder is loaded. Let us add the three files inside the public folder.

We have added three files inside the public folder.

// style.css

body {
  background-color: red
}
// app.js

function add(x)
{
  return x + x;
}
console.log(add(2));

And last one image.

Now, again restart the node server and go to the browser and type the following URLs.

  1. http://localhost:4000/style.css
  2. http://localhost:4000/app.js
  3. http://localhost:4000/Krunal.jpg

You can see the content inside the files in the browser. So, now we are serving the static files in express.

#Multiple Static Assets Directory

We can define the multiple static directories to serve the static files.

For that, we need to define the middleware two times.

app.use(express.static('public'))
app.use(express.static('files'))

In this case, you have two directories 1) public 2) files.

Express looks up the files in the order in which you set a static directory with a express.static middleware function.

To create the virtual path prefix (where the path does not exist in a file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below.

app.use('/content', express.static('public'))

So, here we have defined the prefix called /content.

So, when you access the path to the browser, you need to add the prefix like this.

  1. http://localhost:4000/content/Krunal.jpg
  2. http://localhost:4000/content/style.css
  3. http://localhost:4000/content/app.js

Finally, How To Serve Static Files in Express tutorial is over. Thanks for taking.

The post How To Serve Static Files in Express appeared first on AppDividend.

]]>
https://appdividend.com/2018/11/24/how-to-serve-static-files-in-express/feed/ 0
Node js File System Module Example Tutorial https://appdividend.com/2018/10/09/node-js-file-system-module-example-tutorial/ https://appdividend.com/2018/10/09/node-js-file-system-module-example-tutorial/#comments Tue, 09 Oct 2018 03:18:30 +0000 http://localhost/wordpress/?p=1887 node fs module file system example

Node js File System Module Example Tutorial is today’s leading topic.   The Node.js file system module allows you to work with a file system on your computer. We can include the File System module by using the require() method. The fs module provides the API for interacting with a file system in a manner closely modeled around standard POSIX functions. All node.js file […]

The post Node js File System Module Example Tutorial appeared first on AppDividend.

]]>
node fs module file system example

Node js File System Module Example Tutorial is today’s leading topic.   The Node.js file system module allows you to work with a file system on your computer. We can include the File System module by using the require() method. The fs module provides the API for interacting with a file system in a manner closely modeled around standard POSIX functions. All node.js file system operations have synchronous and asynchronous forms. The asynchronous form always takes the completion callback as its last argument. The arguments passed to a completion callback depend on a method, but the first argument is always reserved for the exception. If the operation was accomplished successfully, then the first argument will be null or undefined.

If you want to learn more about Node.js then check out this course NodeJS – The Complete Guide (incl. MVC, REST APIs, GraphQL)

Node js File System Module Example Tutorial

The everyday use for the File System module is as follows.

  • Read files
  • Create files
  • Update files
  • Delete files
  • Rename files

#Node.js as a File Server

We can require the fs module like the following code.

const fs = require('fs');

Let us take the example of simple file system operation in which we remove the file from disk.

Create one folder called filesystem and get inside that folder.

Now, create one file called acme.js inside the root for just demo purpose.

touch acme.js

We will delete this file using the fs module. So type the following code inside the server.js file.

// server.js

const fs = require('fs');

fs.unlink('acme.js', (err) => {
  if (err) throw err;
  console.log('File system operation successfully executed');
});

Now, run the following command in your terminal.

node server.js

It will give you the output like this and your file will be deleted from the project.

 

Node js File System Module Example Tutorial

#Using try-catch block

You can wrap the above operation in the try-catch block. Let us say we have already deleted the file and again we try to run the command then we will get the following error.

 

node fs module example

So, we need to define the try-catch error mechanism. Also for that, we need to perform the sync operation and not async operation.

// server.js

const fs = require('fs');

try {
    fs.unlinkSync('acme.js');
    console.log('File system operation successfully executed');
  }
catch(e) {
  console.log('Excecuted Catch block');
  console.log(e);
}

 

node filesystem example

So, we have used the fs module’s unlinkSync function.

#File paths

Most fs operations accept file paths that may be specified in the form of a string, a Buffer, or a URL object using the file protocol. String form paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as specified by the process.cwd(). Recreate the acme.js file inside the root. Write the following code inside the server file.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Start your free trial
// server.js

const fs = require('fs');

fs.open('acme.js', 'r', (err, fd) => {
  if (err) throw err;
  console.log('File has opened');
  fs.close(fd, (err) => {
    console.log('File is closing');
    if (err) throw err;
  });
});

#URL object support in node fs module

For most fs module functions, the path or filename argument may be passed as a WHATWG URL object. Only URL objects using the file protocol are supported.

// server.js

const fs = require('fs');
const fileUrl = new URL('file:///acme.js');

fs.readFileSync(fileUrl);

#Open a File using Node fs module

The syntax is following to open a file using node fs module.

fs.open(path, flags[, mode], callback)

Flags

Flags for reading/writing operations are the following.

Flag Description
r Open a file for reading. An exception occurs if a file does not exist.
r+ Open a file for reading and writing. An exception occurs if the file does not exist.
rs Open a file for reading in synchronous mode.
rs+ Open a file for reading and writing, asking the OS to open it synchronously. See notes for ‘rs’ about using this with caution.
w Open a file for writing. The file is created (if it does not exist) or truncated (if it exists).
wx Like ‘w’ but fails if the path exists.
w+ Open a file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
wx+ Like ‘w+’ but fails if the path exists.
a Open a file for appending. The file is created if it does not exist.
ax Like ‘a’ but fails if the path exists.
a+ Open file for reading and appending. The file is created if it does not exist.
ax+ Like ‘a+’ but fails if the path exists.

Let us take an example of opening a file using the node fs module.

// server.js

const fs = require('fs');

fs.open('acme.js', 'r+', function(err, fd) {
  if (err) {
     return console.error(err);
  }
 console.log("File opened successfully!");     
});

You can run the file and see the output. If the file exists then, it will open in the mode of r+.

#Get File Information

Following is the syntax of the method to get the information about a  particular file. 

fs.stat(path, callback)

Let us take an example of node file stat.

// server.js

const fs = require('fs');

fs.stat('acme.js', function (err, stats) {
  if (err) {
      return console.error(err);
  }
  console.log(stats);
  console.log("Got file info successfully!");
  
  // Check file type
  console.log("isFile ? " + stats.isFile());
  console.log("isDirectory ? " + stats.isDirectory());    
});

Run and see the output in the terminal.

 

Get File Information in Node js

#Writing a File using Node fs module.

The syntax is following to write a file in node.js.

fs.writeFile(filename, data[, options], callback)

This method will overwrite the file if a file already exists. If you want to write into an existing file, then you should use another available method.

// server.js

const fs = require('fs');

fs.writeFile('acme.js', 'console.log("hello")', function (err) {
  if (err) throw err;
  console.log('New file acme.js is either created or if exists then updated');
});

#Reading a file using node fs module.

To read a file in node.js, you can use the following syntax.

fs.read(fd, buffer, offset, length, position, callback)

Let us take an example and understand how we can read the file using the node fs.

// server.js

const http = require('http');
const fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('acme.js', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/js'});
    res.write(data);
    res.end();
  });
}).listen(8080);

The above code will spin up the http server and return the content of the file in the webpage. You can access the webpage at this URL: https://localhost:8080.

#Rename Files.

To rename a file with the File System module,  use the fs.rename() method. The fs.rename() method renames the specified file.

// server.js

const fs = require('fs');

fs.rename('acme.js', 'paradox.js', function (err) {
  if (err) throw err;
  console.log('File Renamed!');
});

#Delete Files

To delete a file with the File System module,  use the fs.unlink() method. The fs.unlink() method deletes the specified file.

// server.js

const fs = require('fs');

fs.unlink('paradox.js', function (err) {
  if (err) throw err;
  console.log('File deleted!');
});

Run the file and the file will be removed from the disk.

Finally, Node js File System Module Example Tutorial is over. Thanks for taking.

The post Node js File System Module Example Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/10/09/node-js-file-system-module-example-tutorial/feed/ 1
Moment JS Tutorial With Example From Scratch https://appdividend.com/2018/10/04/moment-js-tutorial-with-example-from-scratch/ https://appdividend.com/2018/10/04/moment-js-tutorial-with-example-from-scratch/#respond Thu, 04 Oct 2018 19:21:54 +0000 http://localhost/wordpress/?p=1839 Getting started with Moment js step by step tutorial example

Moment JS Tutorial With Example From Scratch is today’s leading topic.  The moment.js is an excellent library JavaScript library that helps you manage dates, in the browser and Node.js as well. Working with the dates and times have always been a bit difficult. I have always thought that the JavaScript library for manipulating dates would be very helpful. Moment.js, […]

The post Moment JS Tutorial With Example From Scratch appeared first on AppDividend.

]]>
Getting started with Moment js step by step tutorial example

Moment JS Tutorial With Example From Scratch is today’s leading topic.  The moment.js is an excellent library JavaScript library that helps you manage dates, in the browser and Node.js as well. Working with the dates and times have always been a bit difficult. I have always thought that the JavaScript library for manipulating dates would be very helpful. Moment.js, the impressive JavaScript library for validating, parsing and manipulating dates and times. The moment object in Moment.js is mutable. It means that operations like add, subtract, or set change the original moment object.

If you want to learn more about Node.js then check out this course NodeJS – The Complete Guide (incl. MVC, REST APIs, GraphQL)

Moment JS Tutorial With Example From Scratch

We will use Node.js for this example, as it can be helpful on a client(browser) and server(node.js).

#1: Install Moment.js.

First, create one folder using the following command.

mkdir dates
cd dates

Okay, now create the package.json file using the following command.

npm init -y

Now, install the moment.js using the following command.

npm install moment --save

# or

yarn add moment

 

Moment JS Tutorial With Example From Scratch

Now, create one file called the server.js inside the root and add the following code.

// server.js

const moment = require('moment');

console.log(moment().format('DD/MM/YYYY'));

Save the file and go to the terminal and start the node.js server.

node server

You can see the today’s date as formatted. The moment() gives the current date and time, while format() converts the current date and time to the specified format.

#Get current date and time in the moment.

You can write the following code.

const moment = require('moment');

const date = moment();

console.log(date);

#Manipulating Dates

There are some options for manipulating a moment object. For example, you can add or subtract the days, months, years, etc. You can achieve this manipulation via the add() and subtract() methods.

#Add Syntax

moment().add(Number, String);
moment().add(Duration);
moment().add(Object);

Let us take the following example.

// server.js

const moment = require('moment');

const days = moment().add(15, 'days').format('DD/MM/YYYY');    // adds 15 days to current date
const months = moment().add(12, 'months').format('DD/MM/YYYY');  // adds 12 months to current date
const years = moment().add(10, 'years').format('DD/MM/YYYY');   // adds 10 years to current dateconst date = moment();

console.log('Days', days);
console.log('.........');
console.log('Months', months);
console.log('..........');
console.log('Years', years);

Save the file and run the node server.

 

Moment JS Tutorial

There are some shorthand keys as well if you’re into that whole brevity thing.

Key Shorthand
years y
quarters Q
months M
weeks w
days d
hours h
minutes m
seconds s
milliseconds ms

If you need to add multiple different keys at the same time, then you can pass them in as an object literal.

moment().add(7, 'days').add(1, 'months'); // with chaining
moment().add({days:7,months:1}); // with object literal

#Subtract Syntax

moment().subtract(Number, String);
moment().subtract(Duration);
moment().subtract(Object);

Let us take an example.

// server.js

const moment = require('moment');

const days = moment().subtract(15, 'days').format('DD/MM/YYYY');    // subtracts 15 days to current date
const months = moment().subtract(12, 'months').format('DD/MM/YYYY');  // subtracts 12 months to current date
const years = moment().subtract(10, 'years').format('DD/MM/YYYY');   // subtracts 10 years to current dateconst date = moment();

console.log('Days', days);
console.log('.........');
console.log('Months', months);
console.log('..........');
console.log('Years', years);

#Calculating the Difference Between Dates

Moment.js offers the way to compute the difference between two dates. The difference is computed in milliseconds by default, but can also be returned in days, months, years, etc. To compute a difference, call the diff() method on moment. The diff() method takes a date as its first argument. The unit of time can be specified using an optional second argument.

Let us take an example of the difference between dates.

// server.js

const moment = require('moment');

const dateB = moment('2018-09-10');
const dateC = moment('1993-09-10');

console.log('Difference is ', dateB.diff(dateC, 'days'), 'days');
console.log('Difference is ', dateB.diff(dateC, 'months'), 'months');
console.log('Difference is ', dateB.diff(dateC, 'years'), 'years');

 

javascript moment example tutorial

#Date Comparison Methods

Moment.js also provides date comparison methods. These methods are isBefore()isAfter(), and isSame(). As the names suggest, these methods return Boolean values that are indicating if one date is before, after, or equal to another date.

Let us take an example.

const moment = require('moment');

console.log(moment('2018-09-10').isAfter('2018-09-09')); // returns false
console.log(moment('2018-09-10').isAfter('2018-11-20')); // returns true

#Time from now 

The syntax is following.

moment().fromNow();
moment().fromNow(Boolean);

The conventional way of displaying time is handled by moment#fromNow. It is sometimes called time ago or relative time.

Let us take an example.

// server.js

const moment = require('moment');

console.log(moment([1993, 09, 10]).fromNow()); // 25 years ago

#Parse as an Array

The syntax is the following.

moment(Number[]);

Let us take an example.

// server.js

const moment = require('moment');

moment([1993]);        // January 1st
moment([1993, 10]);     // September 1st
moment([1993, 09, 10]); // September 10th

#Moment Clone

The syntax is the following.

moment(Moment);

Let us take an example.

// server.js

const moment = require('moment');

const a = moment([1993]);
const b = moment(a);
a.year(2018);
console.log(b.year()); // 1993

You can find more about on the moment official documentation.

Finally, Moment JS Tutorial With Example From Scratch is over. Thanks for taking.

The post Moment JS Tutorial With Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/10/04/moment-js-tutorial-with-example-from-scratch/feed/ 0
Express Error Handling Example Tutorial https://appdividend.com/2018/09/16/express-error-handling-example-tutorial/ https://appdividend.com/2018/09/16/express-error-handling-example-tutorial/#comments Sun, 16 Sep 2018 08:22:43 +0000 http://localhost/wordpress/?p=1688 Express Route Handling Example Tutorial

Express Error Handling Example Tutorial is today’s leading topic. One of the most crucial things in a building web applications are error handling. The system will depend on many services, databases, as well as consumers of those services, the unexpected becomes expected. Databases will fail, services become unavailable, server timeout. So your consumers won’t be calling your endpoints with […]

The post Express Error Handling Example Tutorial appeared first on AppDividend.

]]>
Express Route Handling Example Tutorial

Express Error Handling Example Tutorial is today’s leading topic. One of the most crucial things in a building web applications are error handling. The system will depend on many services, databases, as well as consumers of those services, the unexpected becomes expected. Databases will fail, services become unavailable, server timeout. So your consumers won’t be calling your endpoints with the parameters you would expect. To prepare your application for such scenarios, you need to handle errors appropriately.

Error Handling refers to how Express catches and processes errors that occur both synchronously and asynchronously. Express error handling middleware is a powerful tool for consolidating your HTTP error response logic.

If you want to learn more about Node.js then check out this course NodeJS – The Complete Guide (incl. MVC, REST APIs, GraphQL)

Express Error Handling Example Tutorial

Let us take a simple example of error handling.

app.get('/customers', async function(req, res) {
  let customers;
  try {
    customers = await db.collection('Customer').find().toArray();
  } catch (error) {
    res.status(500).json({ error: error.toString() });
  }
  res.json({ customers });
});

Here, we have defined the endpoint called ‘/customers.’ So when any consumer tries to access the route ‘/customers,’ it will go through the try-catch block. If any error occurs then, it will immediately throw an exception and error will be returned otherwise the users will be returned.

The above pattern works well if you have one or two endpoints, but if you’re maintaining dozens of endpoints, then you are going to lose your mind quickly. Let’s say you have decided that HTTP response code 503 is more appropriate than HTTP 500; so you are going to have to change that for every single endpoint.

#Catching Express Errors

It is essential to assure that Express catches all the errors that occur while running route handlers and middleware. Errors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it.

Errors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it. For example:

app.get("/", function (req, res) {
  throw new Error("Opps!! Something went wrong"); // Express will catch this on its own.
});

For errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the next() function, where Express will catch and process them. For example:

app.get("/", function (req, res, next) {
  fs.readFile("/file-does-not-exist", function (err, data) {
    if (err) {
      next(err); // Pass errors to Express.
    }
    else {
      res.send(data);
    }
  });
});

#Writing error handling Middleware

Express middleware is divided into different types based on the number of arguments your middleware function takes. The middleware function that takes four arguments which are classified as “error handling middleware,” and will only get called if an error occurs. Define the error-handling middleware functions in the same way as other middleware functions are defined, except error-handling functions, have four arguments instead of three: (err, req, res, next). For example:

app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something went wrong!!');
});

You define error-handling middleware last, after other app.use() and routes calls; for example:

const bodyParser = require('body-parser');
const methodOverride = require('method-override');

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something went wrong!!');
});

The only way to report errors to Express for use with error handlers is using the third argument to standard middleware, the next() function.

Now, let us take a practical example.

#1: Create Express Project

Create an express project folder.

mkdir errorexpress && cd errorexpress

Open the project in VSCode.

code .

Now, initialize the package.json file.

npm init -y

Install express using the following command.

npm install express --save

# or

yarn add express

#2: Setup Express server.

Okay, now inside the root,  create one file called server.js.

// server.js

const app = require('express')();
const PORT = process.env.PORT = 3000;


app.listen(PORT, () => {
  console.log('Server is running at PORT',PORT);
});

Now, add the exception code.

// server.js

const app = require('express')();
const PORT = process.env.PORT = 3000;

app.get('*', function(req, res, next) {
  setImmediate(() => { 
    next(new Error('Ohh!! Something went wrong')); 
  });
});

app.use(function(error, req, res, next) {
  res.json({ message: error.message });
});

app.listen(PORT, () => {
  console.log('Server is running at PORT',PORT);
});

Save the file and go to the terminal and start the node server.

node server

 

Express Error Handling Example Tutorial

Now go to the browser and hit this URL: http://localhost:3000

You will see the JSON response with an error message. So this is how we can write a middleware that throws an error.

#Use With Async/Await in Error Middleware

Express was mostly written 2011-2014, before ES6, and it still lacks a good answer for how to handle the async/await keywords. We can write the above code in async/await manner.

// server.js

const app = require('express')();
const PORT = process.env.PORT = 3000;

function wrapAsync(fn) {
  return function(req, res, next) {
    fn(req, res, next).catch(next);
  };
}

app.get('*', wrapAsync(async function(req, res) {
  await new Promise(resolve => setTimeout(() => resolve(), 50));
  throw new Error('Oppss!! Something went wrong');
}));

app.use(function(error, req, res, next) {
  res.json({ message: error.message });
});

app.listen(PORT, () => {
  console.log('Server is running at PORT',PORT);
});

Here, with a little helper function, you can tie async/await errors in with Express error handling middleware. Remember that async functions return promises, so you need to make sure to .catch() any errors and pass them to next():

// server.js

const app = require('express')();
const PORT = process.env.PORT = 3000;

function wrapAsync(fn) {
  return function(req, res, next) {
    fn(req, res, next).catch(next);
  };
}

app.get('*', wrapAsync(async function(req, res) {
  await new Promise(resolve => setTimeout(() => resolve(), 50));
  throw new Error('Oppss!! Something went wrong');
}));

app.use(function(error, req, res, next) {
  res.json({ message: error.message });
});

app.listen(PORT, () => {
  console.log('Server is running at PORT',PORT);
});

Finally, Express Error Handling Example Tutorial is over. Thanks for taking.

The post Express Error Handling Example Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/09/16/express-error-handling-example-tutorial/feed/ 3
Express Router Tutorial Example From Scratch https://appdividend.com/2018/09/15/express-router-tutorial-example-from-scratch/ https://appdividend.com/2018/09/15/express-router-tutorial-example-from-scratch/#respond Sat, 15 Sep 2018 18:23:25 +0000 http://localhost/wordpress/?p=1676 Express Router Tutorial

Express Router Tutorial Example From Scratch is today’s leading topic. Routing refers to how an application’s endpoints (URIs) respond to client requests. Express is the popular Node.js web framework. Amongst its functionality as it provides a wrapper for Routing. The Express Router class helps in the creation of route handlers. Express apps utilize routers that are essentially containers for a set […]

The post Express Router Tutorial Example From Scratch appeared first on AppDividend.

]]>
Express Router Tutorial

Express Router Tutorial Example From Scratch is today’s leading topic. Routing refers to how an application’s endpoints (URIs) respond to client requests. Express is the popular Node.js web framework. Amongst its functionality as it provides a wrapper for Routing. The Express Router class helps in the creation of route handlers. Express apps utilize routers that are essentially containers for a set of middleware. We can put this middleware holder only on a specific route, which allows us to keep our logic in separate files and bring them together on our terms.

If you want to learn more about Node.js then check out this course NodeJS – The Complete Guide (incl. MVC, REST APIs, GraphQL)

Express Router Tutorial Example From Scratch

First of all, we will create a project for the express router example tutorial.

#1: Create an express project.

Create one project folder and go inside that folder.

mkdir erouter && cd erouter

Now, initialize the package.json file using the following command.

npm init -y

 

Express Router Tutorial Example From Scratch

Now, install the express using the following command.

npm install express --save

# or

yarn add express

#2: Let us write the first express route.

Now, inside the root folder. Create one file called server.js and add the following code.

// server.js

const express = require("express");
const app = express();
const PORT = process.env.PORT = 3000;

let router = express.Router();

router.get('/',function(req,res){
  res.json({'message' : 'Ping Successfull'});
});

app.use('/api',router);

app.listen(PORT,function(){
  console.log('Server is running at PORT:',PORT);
});

First, we have imported all the required modules and then create an object of a router and then defined on the root route. Then we have used the middleware saying that, if any request comes with the ‘/api’ then it will call the router function with its route. So in our case, we will get a JSON response.

So this was the example of basic routing that we used to do when we create a web application with express on Node.js platform.

#Route Methods

Express supports the main following routing methods.

  1. GET
  2. POST
  3. PUT
  4. HEAD
  5. DELETE
  6. OPTIONS

There are still other methods, but mainly we used the above methods in a web application. There is a routing method called app.all() which is not derived from any HTTP method. The routing method gets loaded for functions at a specified path for all of the request methods.

The route path is used to define an endpoint where requests can be made. It is like a backend endpoint.  In the Express, route paths can be string patterns or regular expressions.

In the above example, the route path is the below.

// server.js

router.get('/',function(req,res){
  res.json({'message' : 'Ping Successfull'});
});

Here, the router path is “/.”

The route parameters are used to capture the values that are specified to a particular position in the URL. They are called the URL segments. The values obtained are made available in a req.params object, using the name of the route parameter specified in the path as the keys of the values.

Route parameter is significant in functionality like edit, update, and delete. We generally pass the ID on the parameter and extract from the request. The syntax is like this.

http://localhost:3000/api/user/:id

Now, at Express Router, we can access the ID using the following code.

http://localhost:3000/api/user/1

In the req.params, the following will be available: { “id”: “1” }

So, we can access the 1 using the following code.

req.params.id

#Express Route POST Request

The basic syntax of express post route is the following.

// server.js

router.post('/', function(req, res){
   res.send('It's a post route, grab the data and save in the Mongo');
});

Inside the router post method, we save the data that come from req and extract that data from req and save the data inside the database.

Just like the following code.

router.route('/store').post(function (req, res) {
  let model = new Model(req.body);
  model.save()
    .then(game => {
    res.status(200).json({'model': 'Your data is saved'});
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});

So, here we have used the Mongoose model to save the data in the MongoDB database. It is just a real-time example that will show you how you can create your post request and save the data in the database.

#Router-level middleware

Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of express.Router().

// server.js

const app = express();
const router = express.Router();

router.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});

router.use('/user/:id', function (req, res, next) {
  console.log('Request URL:', req.originalUrl);
  next();
}, function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});

Finally, Express Router Tutorial Example From Scratch is over.

The post Express Router Tutorial Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/09/15/express-router-tutorial-example-from-scratch/feed/ 0
How To Create Express HTTPS Server With A Self-Signed Certificate https://appdividend.com/2018/09/10/create-express-https-server-with-a-self-signed-certificate/ https://appdividend.com/2018/09/10/create-express-https-server-with-a-self-signed-certificate/#respond Mon, 10 Sep 2018 12:23:14 +0000 http://localhost/wordpress/?p=1636 Create Express HTTPs Server in Nodejs

How To Create Express HTTPS Server With A Self-Signed Certificate is today’s leading topic. If we need start our node.js server on node.js then to be able to serve a site on HTTPS from localhost you need to create a self-signed certificate. The self-signed certificate will be enough to establish a secure HTTPS connection, although browsers […]

The post How To Create Express HTTPS Server With A Self-Signed Certificate appeared first on AppDividend.

]]>
Create Express HTTPs Server in Nodejs

How To Create Express HTTPS Server With A Self-Signed Certificate is today’s leading topic. If we need start our node.js server on node.js then to be able to serve a site on HTTPS from localhost you need to create a self-signed certificate. The self-signed certificate will be enough to establish a secure HTTPS connection, although browsers will complain that the certificate is self-signed and as such it’s not trusted. It is still great for development purposes. Let us say, if you are working with React Native or other iOS development then you need an API point, and if the API point is served via HTTPs then it will be straightforward otherwise it gets complicated to get the response from the server. I have found very painful while developing frontend and backend apps. So it can be beneficial in these scenarios.

If you want to learn more about Node.js then check out this course NodeJS – The Complete Guide (incl. MVC, REST APIs, GraphQL)
Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program

Create Express HTTPS Server With A Self-Signed Certificate

Okay, first you must have installed the OpenSSL installed on your machine. If not, on a Mac you can install it using brew install OpenSSL if you use Homebrew. Otherwise, search on Google “how to install openssl on ”.

If you want to upgrade your current OpenSSL version, then update the OpenSSL using the following command.

brew upgrade openssl

Once an OpenSSL is installed, hit this command.

openssl req -nodes -new -x509 -keyout server.key -out server.cert

You will prompt for some answers. Give the answers one by one.

 

Create Express HTTPS Server With A Self-Signed Certificate

That’s it! Now you have two files in the folder where you ran the following command.

  • server.cert is the self-signed certificate file.
  • server.key is the private key of the certificate.

Both files will be needed to establish the HTTPS connection, and depending on how you are going to set up your server, the process to use them will be different.

Those files need to be put in place reachable by the application; then you need to configure the server to use them.

This is an example using the https core module and Express.

// server.js

const https = require('https')
const app = express()

app.get('/', (req, res) => {
  res.send('Hello HTTPS!')
})

https.createServer({}, app).listen(3000, () => {
  console.log('Listening...')
})

Now initialize the package.json file using the following command.

npm init -y

Okay, now install the express using the following command.

npm install express --save

Okay, finally our code with the certificates is the following.

// server.js

const https = require('https');
const express = require('express');
const fs = require('fs');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello HTTPS!')
})

https.createServer({
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.cert')
}, app).listen(3000, () => {
  console.log('Listening...')
});

Save the file and go to the terminal.

node server

Go to the browser and hit this URL: https://localhost:3000.

At first, it will say, it is insecure because it is self-signed but ignores this error, and now you can access the content. The looking is not great on the browser because it will say insecure but trust me for a local developing purpose; it is excellent.

Finally, How To Create Express HTTPS Server With A Self-Signed Certificate tutorial is over. Thanks for taking.

The post How To Create Express HTTPS Server With A Self-Signed Certificate appeared first on AppDividend.

]]>
https://appdividend.com/2018/09/10/create-express-https-server-with-a-self-signed-certificate/feed/ 0