DEV Community

Prasad Saya
Prasad Saya

Posted on

Notes about a NodeJS program I wrote at work - 22nd Feb, 2023.

The NodeJS program is about preparing data and sending a POST request to an API external to this app. The app receives a response from the request for further processing. An aspect of this app is making the POST request at a regular interval, for example every 6 hours. Finally, I needed to log the API calls to a file.

In this post I discuss, in brief, the various libraries used to accomplish the task.

How to make a job run every n hours?

I used a cron task scheduler library, the node-cron. The scheduler code looked like this:

const cron = require("node-cron");
const CRON = "0 0 */6 * * *";
cron.schedule(CRON, async () => {
    console.log("Making the API request.");
    // ...
});
Enter fullscreen mode Exit fullscreen mode

How to make a POST request using form data?

For this functionality, I used the form-data library. This allowed sending form data with an uploaded file and also set custom headers. For example, creating the form data:

const FormData = require("form-data");
const formData = new FormData();
formData.append("mydata", "some data");
formData.append("myfile", fs.createReadStream("abc.xyz"));
const options = { method: "POST", body: formData, headers: { myhdr: "hdr value" } };
Enter fullscreen mode Exit fullscreen mode

Send the request and receive a response using node-fetch using the earlier created form data:

const fetch = require("node-fetch");
const resp = await fetch("http://www.example.com/someapi", options);
const json_data = await resp.json();
// Do something with the response data here ...
Enter fullscreen mode Exit fullscreen mode

An aspect to note is that the functionality (or similar) of the fetch npm package is the implementation in NodeJS 17.x fetch.


What logger?

The logging needed to be both in the console as well as to a file. The logged message included a timestamp too. I used the winston logging library. The logger code looked like this:

const winston = require("winston");
const logger = winston.createLogger({
    level: "info",
    format: winston.format.combine(winston.format.timestamp(), winston.format.json()),
    transports: [
        new winston.transports.File({ filename: "log_file_name.log" }),
        new winston.transports.Console(),  
    ],
});

logger.info({ message: "Logger started" });
Enter fullscreen mode Exit fullscreen mode

Conclusion:

I had used various libraries to accomplish a task. I note that the logging is the most common task and an important aspect of developing apps.


Top comments (0)