Capture Desktop Screenshots using Node.js and Upload to Another Server via API: A Comprehensive Guide

Capture Desktop Screenshots using Node.js and Upload to Another Server via API: A Comprehensive Guide

const express = require('express');
const ejs = require('ejs');
const path = require('path');
const axios = require('axios');
const handlebars = require('hbs');
const bodyParser = require('body-parser');
const fs = require('fs');
const multer = require('multer');
const pdf = require('html-pdf');
const upload = multer({ dest: 'uploads/' }).single('csv');
const session = require('express-session');
const screenshot = require('screenshot-desktop');
const { Readable } = require('stream');
const { Blob } = require('buffer');

const expressApp = express();

  expressApp.use(express.static(path.join(__dirname, 'public')));

  expressApp.set('view engine', 'hbs');
  expressApp.set('views', path.join(__dirname, 'views'));

  expressApp.use(bodyParser.urlencoded({ extended: true }));

function takeScreenshot() {


var datetime = Date.now();

  // Capture the screenshot
  screenshot({ screen: 'main', filename: `${datetime}.png` })
  .then((imgPath) => {

    // Example usage
    const imagePath = `${datetime}.png`;
    const uploadUrl = 'http://erp.test/api/save_screenshort';

    uploadImage(imagePath, uploadUrl);

  })
  .catch((err) => {
    console.error(`Failed to capture screenshot: ${err}`);
  });
}

function callScreenshot() {
  const delay = Math.random() * 1 * 60 * 1000; // 5 minutes

  setTimeout(() => {
    takeScreenshot();
    callScreenshot(); // Call the function again to repeat the process
  }, delay);

}


callScreenshot();


// update images to erp portal start

// Function to convert a Buffer to a Blob
function bufferToBlob(buffer) {
  const readable = new Readable();
  readable._read = () => {};
  readable.push(buffer);
  readable.push(null);

  return new Blob([readable.read()]);
}


// Function to upload an image using Axios
async function uploadImage(imagePath, uploadUrl) {
  try {
    const imageBuffer = fs.readFileSync(imagePath);
    const imageBlob = bufferToBlob(imageBuffer);

    const formData = new FormData();
    formData.append('image', imageBlob, imagePath);

    const headers = {
      'Content-Type': 'multipart/form-data',
    };

    const response = await axios.post(uploadUrl, formData, {
      headers: headers,
    });

    console.log('Image uploaded successfully:', response.data.message);
  } catch (error) {
    console.error('Error while uploading image:', error.message);
  }
}

Did you find this article valuable?

Support Mandeep Singh Blog by becoming a sponsor. Any amount is appreciated!