Node JS

Auto Refresh the web page using Node JS and PUG

Recently I was working on the Web Framework project using PowerShell and Python which eventually made me to learn more. My requirement was to refresh the web page which helps a small monitoring team. In this blog post I will share the base logic and yes it requires improvement and in my next blog I will share the complete solution.

Requirement: Auto refresh the page at certain interval!

For a demo I used Get-Date cmdlet (Ticks and Second property)

Get-Date | Select-Object * | ConvertTo-Json

Output is as expected!

{
    "DisplayHint":  2,
    "DateTime":  "Wednesday, August 15, 2018 10:31:06 AM",
    "Date":  "\/Date(1534305600000)\/",
    "Day":  15,
    "DayOfWeek":  3,
    "DayOfYear":  227,
    "Hour":  10,
    "Kind":  2,
    "Millisecond":  926,
    "Minute":  31,
    "Month":  8,
    "Second":  6,
    "Ticks":  636699258669266846,
    "TimeOfDay":  {
                      "Ticks":  378669266846,
                      "Days":  0,
                      "Hours":  10,
                      "Milliseconds":  926,
                      "Minutes":  31,
                      "Seconds":  6,
                      "TotalDays":  0.43827461440509258,
                      "TotalHours":  10.518590745722221,
                      "TotalMilliseconds":  37866926.6846,
                      "TotalMinutes":  631.11544474333334,
                      "TotalSeconds":  37866.926684599995
                  },
    "Year":  2018
}

Take a look at the server.js file!

app.get("/demo", function (request, response) {
    child = spawn('powershell.exe',
        [ "C:\\Projects\\RealTimeApp\\scripts\\demo.ps1" ])
    child.stdout.on('data', function (data) {
        var result = JSON.parse(data);
        response.render('data', {
            dateTime : result
        })
    })
});

Let me brief the above demo route = We are calling the PowerShell file using the child_process inbuilt module and and rendering the data in the web page. Here, result is the JSON parsed values which is assigned to dateTime object.

Now, see how it is used in the PUG file.

body
    h1 Ticks #{dateTime.Ticks}
    h2 Second #{dateTime.Second}

Cool Right? Here comes the auto refresh logic!

setTimeout(function(){
    location=''
},6000)

We call this autoRefresh.js using the script include in PUG!

<!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 Document
        style.
            h1 {
                color:black
            }
            h2 {
                color: royalblue
            }
    body
        h1 Ticks #{dateTime.Ticks}
        h2 Second #{dateTime.Second}
    script
        include ./autoRefresh.js

Enjoy Node and PUG! In this blog

Leave a Reply

Your email address will not be published. Required fields are marked *