How to Build a Cron Job with Node js

How to Build a Cron Job with Node js

Build a simple cron scheduler with node.js. This video should get you on your way to automating your task on a computer.

There comes a time in our app development where we will want to automate some certain aspects of our project. Like, run some scripts outside the scope of the project.

Most of the projects I have built for my clients, I built my cron jobs in PHP and used GoDaddy to set up the cron jobs.

In this post we will learn how to set up cron jobs in Node.js applications.

Using setTimeout

setTimeout is the best bet of all Nodejs APIs to use in scheduling execution time of code snippets because it used to defer execution of a function to until a particular time. The setTimeout API takes two parameters:

setTimeout(fn, ms)

The fn parameter is the callback function that is executed when the time ms has elapsed.

The ms is the time in milliseconds that the function must wait before executing the function in the fn param.

Lets see some examples:

setTimeout(()=>console.log("Done !!"), 1000)

We scheduled a function ()=>console.log("Done !!") to execute after the passage of 1 second. Note, we said the time is in milliseconds so passing 1000 milliseconds above is equal to 1 second.

Doing the Math:

1000 miili = 1000 * 10^-3 = 1000
                            ---- = 1
                            1000

So, after 1 second we will see Done !! in our terminal.

Now, let’s create our own cron job using setTimeout API. Note, cron-jobs run after a specified amount of time continuously.

function cron(ms, fn) {
    function cb() {
        clearTimeout(timeout)
        timeout = setTimeout(cb, ms)
        fn()
    }
    let timeout = setTimeout(cb, ms)
}

What did we do above? The cron function takes in the time of the execution and the callback function. First, we setup up the timeout with the setTimeout API passing in the params ms and cb. setTimeout returns a reference to its timeout so we save it in the timeout variable. The function cb we passed to setTimeout is an internal function cb which forms a closure around the ms and fn parameters. The function when called after the ms elapsed, clears the timeout by calling the clearTimeout API passing the timeout variable we saved earlier, then set up another timeout saving the timeout reference to the timeout variable, then last it calls the function fn.

So, now with this our implementation we continuously run the cron without exiting.

Let’s test the cron function:

cron(20000, () => console.log("cron job"))

We will see cron job logged in the terminal after every 2 seconds.

[email protected] MINGW64 /c/wamp/www/developerse/projects/post_prjs/chat-app/server (master)
$ node cron
cron job
cron job
cron job
cron job
cron job
cron job
...
cron job

This will continue to forever until we press Ctrl + C in our terminal.

Now, crons are used in servers, let’s port this our cron function to Express server.

First setup the Node environ and install the Express module

mkdir cron-express
cd node-express
npm init -y
npm install express
touch cron.js

Open cron.js and add the follwoing contents:

// require dependencies
const express = require('express')
const log = console.log
// initialize express and port number
const app = express()
const port = 3000
// configure routes
app.get("/", (req, res) => {
    res.send("index route")
})
// start the server
app.listen(port, () => log(`Server: PORT ${port} active`))

We will edit the function cron to be used as a middleware in Express.

function cron(ms, fn) {
    function cb() {
        clearTimeout(timeout)
        timeout = setTimeout(cb, ms)
        fn()
    }
    let timeout = setTimeout(cb, ms)
    return () => {}
}

We return an empty arrow function in the end so our cron implementation will run immediately on the start of the Express server.

Let’s plug it in in our Express code:

// require dependencies
const express = require('express')
const log = console.log
// initialize express and port number
const app = express()
const port = 3000
// cron function
function cron(ms, fn) {
    function cb() {
        clearTimeout(timeout)
        timeout = setTimeout(cb, ms)
        fn()
    }
    let timeout = setTimeout(cb, ms)
    return () => {}
}
// setup middlewares
cron(20000, () => log("cron job"))
// configure routes
app.get("/", (req, res) => {
    res.send("index route")
})
// start the server
app.listen(port, () => log(`Server: PORT ${port} active`))

Running the server, we will have this:

[email protected] MINGW64 /c/wamp/www/developerse/projects/post_prjs/chat-app/server (master)
$ node cron
Server: PORT 3000 active
cron job
cron job
cron job

Our cron job continuously runs while the server waits for a request.

Using node-cron

We can easily plug-in cron libraries to easily enable us to run crons in Express without writing our custom code. node-cron is one of the best libraries in npm that provides an efficient implementation of cron jobs in Nodejs.

To use node-cron we install it:

npm install node-cron

Import node-cron and schedule a task

const cron = require('node-cron')
cron.schedule("* * * * *",()=> {
    log("logs every minute")
})

This will run every minute. The schedule method is used to schedule a cron and it takes the duration and the function.

Using it in our Express it will look like this:

// require dependencies
const cron = require('node-cron')
const express = require('express')
const log = console.log
// initialize express and port number
const app = express()
const port = 3000
// setup cron job
cron.schedule("* * * * *", () => {
    log("logs every minute")
})
// configure routes
app.get("/", (req, res) => {
    res.send("index route")
})
// start the server
app.listen(port, () => log(`Server: PORT ${port} active`))
Conclusion

We saw how easy it is to set up a cron job in Nodejs and to use it in Express server. We first wrote our own custom cron logic using the setTimeout API, that really opened our eyes on how crons works. They continually run while the other code executes or listens for network requests.

We also, saw how to use the node-cron library to easily set up a cron.

If you have any question regarding this or anything I should add, correct or remove, feel free to comment below. Thanks !!! 🍻

How to get started Internationalization in JavaScript with NodeJS

How to get started Internationalization in JavaScript with NodeJS

Tutorial showing how to use the Intl JS API in NodeJS (i18n). We'll install a module to unlock the Intl API languages for Node and test out RelativeTimeFormat to translate and localise relative times in JavaScript.

Tutorial showing how to use the Intl JS API in NodeJS (i18n). We'll install a module to unlock the Intl API languages for Node and test out RelativeTimeFormat to translate and localise relative times in JavaScript. I'll tell you how to get started with the built-in internationalization library in JS for Node 12 and higher. We'll change the locale to see how the translation works and test different BCP 47 language tags.

Internationalization is a difficult undertaking but using the Intl API is an easy way to get started, it's great to see this new API in the JS language and available for use. Soon, you'll be able to have confidence using it in the browser as modern browsers support the major Intl features. Have a look at the browser compatibility charts to see which browsers and versions of node are supported.

Use Intl.RelativeTimeFormat for language-sensitive relative time formatting.
#javascript #nodejs #webdevelopment

MDN Documentation:

https://developer.mozilla.org/en-US/d...

Full ICU NPM package:

https://www.npmjs.com/package/full-icu

JavaScript Tutorial: if-else Statement in JavaScript

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

JavaScript’s conditional statements:

  • if
  • if-else
  • nested-if
  • if-else-if

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:
if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block 
// will consider only statement1 to be inside 
// its block.

Flow chart:

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If statement 

var i = 10; 

if (i > 15) 
document.write("10 is less than 15"); 

// This statement will be executed 
// as if considers one statement by default 
document.write("I am Not in if"); 

< /script> 

Output:

I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}


Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If-else statement 

var i = 10; 

if (i < 15) 
document.write("10 is less than 15"); 
else
document.write("I am Not in if"); 

< /script> 

Output:

i is smaller than 15
  • nested-if A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:
if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
}

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate nested-if statement 

var i = 10; 

if (i == 10) { 

// First if statement 
if (i < 15) 
	document.write("i is smaller than 15"); 

// Nested - if statement 
// Will only be executed if statement above 
// it is true 
if (i < 12) 
	document.write("i is smaller than 12 too"); 
else
	document.write("i is greater than 15"); 
} 
< /script> 

Output:

i is smaller than 15
i is smaller than 12 too
  • if-else-if ladder Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;


Example:

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 

var i = 20; 

if (i == 10) 
document.wrte("i is 10"); 
else if (i == 15) 
document.wrte("i is 15"); 
else if (i == 20) 
document.wrte("i is 20"); 
else
document.wrte("i is not present"); 
< /script> 

Output:

i is 20

How to Retrieve full Profile of LinkedIn User using Javascript

How to Retrieve full Profile of LinkedIn User using Javascript

I am trying to retrieve the full profile (especially job history and educational qualifications) of a linkedin user via the Javascript (Fetch LinkedIn Data Using JavaScript)

Here we are fetching LinkedIn data like Username, Email and other fields using JavaScript SDK.

Here we have 2 workarounds.

  1. Configuration of linkedIn developer api
  2. Javascript Code to fetch records

Configuration of linkedIn developer api

In order to fetch records, first we need to create developer api in linkedin which will act as token/identity while fetching data from other linkedin accounts.

So to create api, navigate to https://linkedin.com/developer/apps and click on 'Create Application'.

After navigating, fill in details like name, description and other required fields and then submit.

As we submit, it will create Client ID and Client Secret shown below, which we will be using in our code while communicating to fetch records from other LinkedIn account.

Note: We need to provide localhost Url here under Oauth 2.0. I am using my localhost, but you can probably use other production URLs under Oauth 2.0 where your app is configured. It will make your api  consider the Url as trusted which fetching records.

Javascript Code to fetch records

For getting user details like first name, last name,User image can be written as,

<script type="text/javascript" src="https://platform.linkedin.com/in.js">  
    api_key: XXXXXXX //Client ID  
    onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load  
    authorize: true  
</script>  
<script type="text/javascript">  
    function OnLinkedInFrameworkLoad() {  
        IN.Event.on(IN, "auth", OnLinkedInAuth);  
    }  
  
    function OnLinkedInAuth() {  
        IN.API.Profile("me").result(ShowProfileData);  
    }  
  
    function ShowProfileData(profiles) {  
        var member = profiles.values[0];  
        var id = member.id;  
        var firstName = member.firstName;  
        var lastName = member.lastName;  
        var photo = member.pictureUrl;  
        var headline = member.headline;  
        //use information captured above  
        var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: " + lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline + "<p/>"  
        document.getElementById('profiles').innerHTML = stringToBind;  
    }  
</script>    

Kindly note we need to include 'https://platform.linkedin.com/in.js' as src under script type as it will act on this Javascript SDK provided by Linkedin.

In the same way we can also fetch records of any organization with the companyid as keyword.

<head>  
    <script type="text/javascript" src="https://platform.linkedin.com/in.js">  
        api_key: XXXXXXX ////Client ID  
        onLoad: onLinkedInLoad  
        authorize: true  
    </script>  
</head>  
  
<body>  
    <div id="displayUpdates"></div>  
    <script type="text/javascript">  
        function onLinkedInLoad() {  
            IN.Event.on(IN, "auth", onLinkedInAuth);  
            console.log("On auth");  
        }  
  
        function onLinkedInAuth() {  
            var cpnyID = XXXXX; //the Company ID for which we want updates  
            IN.API.Raw("/companies/" + cpnyID + "/updates?event-type=status-update&start=0&count=10&format=json").result(displayCompanyUpdates);  
            console.log("After auth");  
        }  
  
        function displayCompanyUpdates(result) {  
            var div = document.getElementById("displayUpdates");  
            var el = "<ul>";  
            var resValues = result.values;  
            for (var i in resValues) {  
                var share = resValues[i].updateContent.companyStatusUpdate.share;  
                var isContent = share.content;  
                var isTitled = isContent,  
                    isLinked = isContent,  
                    isDescription = isContent,  
                    isThumbnail = isContent,  
                    isComment = isContent;  
                if (isTitled) {  
                    var title = isContent.title;  
                } else {  
                    var title = "News headline";  
                }  
                var comment = share.comment;  
                if (isLinked) {  
                    var link = isContent.shortenedUrl;  
                } else {  
                    var link = "#";  
                }  
                if (isDescription) {  
                    var description = isContent.description;  
                } else {  
                    var description = "No description";  
                }  
                /* 
                if (isThumbnailz) { 
                var thumbnailUrl = isContent.thumbnailUrl; 
                } else { 
                var thumbnailUrl = "http://placehold.it/60x60"; 
                } 
                */  
                if (share) {  
                    var content = "<a target='_blank' href=" + link + ">" + comment + "</a><br>";  
                    //el += "<li><img src='" + thumbnailUrl + "' alt=''>" + content + "</li>";  
                    el += "<li><div>" + content + "</div></li>";  
                }  
                console.log(share);  
            }  
            el += "</ul>";  
            document.getElementById("displayUpdates").innerHTML = el;  
        }  
    </script>  
</body>  

We can get multiple metadata while fetching records for any any organization. We can get company updates as shown below.

Conclusion

We can also fetch any company specific data like company job updates/post, total likes, comments, and number of views along with a lot of metadata we can fetch which I have shown below.

Thank you for reading !