1

I am using NodeJS. I am checking the response status of https://encrypted.google.com/ . I have a file in my project. Let's call it ,

status.js :-

var https = require('https');

https.get('https://encrypted.google.com/', function(res) {
  console.log("statusCode: ", res.statusCode); 
  console.log("headers: ", res.headers);

  res.on('data', function(d) {
    process.stdout.write(d);
  });

}).on('error', function(e) {
  console.error(e);
});

Now, I also have server.js file and node is running through it.

node server.js

I want to execute the status.js till the nodeserver runs. That means, it should continously check the status of https://encrypted.google.com/. What is the recommended way to do this ?

server.js :-

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

// create express app
const app = express();

// listen for requests
app.listen(3000, () => {
    console.log("Server is listening on port 3000");
});

2 Answers 2

1

Use a setInterval and execute the code from status.js. When your status is resolved as you want it, clear the interval via clearInterval.

Sign up to request clarification or add additional context in comments.

Comments

0

Ok. I think the adding an event emitter was a bit unnecessary. You can try this out. This is the typescript file. For javascript replace the imports with the respective require statements.

server.ts

import express from "express";
import http from 'http';
import { getHttpsRequests } from "./status";

//Create an http server with  the express app
const app = express();
const server = new http.Server(app);
let interval;

// listen for requests
server.listen(4300);
server.on('listening', () => {
    interval = setInterval(() => {
        getHttpsRequests();
    }, 1000);
});

//register a close event on server
server.on('close', () => {
    console.log('closing server');
    clearInterval(interval);
});

status.ts

var https = require('https');

export function getHttpsRequests() {
    //your code goes here
    https.get('https://encrypted.google.com/', function (res) {
        console.log("statusCode: ", res.statusCode);
        console.log("headers: ", res.headers);

       res.on('data', function (d) {
            process.stdout.write(d);
        });

    }).on('error', function (e) {
        console.error(e);
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.