Search code examples
node.jsexpressapify

Checking the status of Apify during the execution of any process


Let's assume a server

const Apify = require("apify");
const express = require("express");

const app = express();

app.get("/run", async (_, res) => {
  Apify.main(async () => {
    // Let the actor run for an hour.
    await Apify.utils.sleep(60 * 60 * 1000);
  });
  res.redirect("/");
});

app.get("/state", async (req, res) => {
  const pageHtml = `

<html>
    <head><title>Example</title></head>
    <body>
       <pre>${JSON.stringify(Apify.utils.log)}</pre>
    </body>
</html>
`;
  res.send(pageHtml);
});

app.listen(3000, () => {
  console.log(`Application is listening at URL ${APIFY_CONTAINER_URL}.`);
});

It doesn't do anything except express and apify working.

How can I catch the state of Apify?

I need to know

  • is there a working actor now?
  • is there a sleep state?
  • what is main state of Apify now?

No Apify Cloud.


Solution

  • you need to wrap all your code inside Apify.main:

    const Apify = require("apify");
    const express = require("express");
    
    Apify.main(async () => {
        const app = express();
    
        app.get("/run", async (_, res) => {
          res.redirect("/");
        });
        
        app.get("/state", async (req, res) => {
          const pageHtml = `
        
        <html>
            <head><title>Example</title></head>
            <body>
               <pre>${JSON.stringify(Apify.utils.log)}</pre>
            </body>
        </html>
        `;
          res.send(pageHtml);
        });
        
        app.listen(3000, () => {
          console.log(`Application is listening at URL ${APIFY_CONTAINER_URL}.`);
        });
        
        await new Promise(() => {}); // wait forever    
    });
    

    you can use the bare minimum example here for future reference https://github.com/metalwarrior665/apify-utils/blob/master/examples/express-server.js