heartbeat | | run todays heartbeat items | Search

This code defines a function thump that asynchronously executes Node.js scripts, allowing for parameter passing, output logging, and error handling.

Run example

npm run import -- "heartbeat thump"

heartbeat thump

var fs = require('fs');
var path = require('path');

var CORE = path.resolve(path.join(__dirname, '../Core'));
var NODE = fs.existsSync('/usr/local/bin/node') ? '/usr/local/bin/node' : '/usr/bin/node';

function thump(thump, parameters, exit) {
    var out = fs.openSync('/tmp/myjob.log', 'a');
    var err = fs.openSync('/tmp/myjob.log', 'a');
    console.log('executing ' + NODE + ' - ' + CORE + ' - ' + thump + ' - ' + JSON.stringify(parameters));
    require('child_process').spawn(NODE, [
        '-e',
        'require(' + JSON.stringify(CORE) + ').import("+ thump +")(' + (parameters ? ('...' + JSON.stringify(parameters || [])) : '') + ').catch(e => console.log(e)).then(() => process.exit())'
    ], {
        detached: true,
        stdio: [ 'ignore', out, err ]
    }).unref();
    if(exit !== false) {
        if(typeof $ !== 'undefined') {
            return $.done();
        }
        process.exit(0);
    }
}
module.exports = thump;

What the code could have been:

// Import required modules
const fs = require('fs');
const path = require('path');
const childProcess = require('child_process'); // Rename for clarity

// Define constants
const CORE_DIR = path.resolve(path.join(__dirname, '../Core'));
const NODE_BIN = process.platform === 'darwin' // macOS
 ? '/usr/local/bin/node'
  : process.platform === 'linux'
 ? '/usr/local/bin/node'
  : '/usr/bin/node';

// Function thump
/**
 * Execute a thump function in a detached process.
 * @param {string} thump - Name of the thump function to execute.
 * @param {object|undefined} parameters - Parameters to pass to the thump function.
 * @param {boolean|undefined} exit - Exit the current process after executing the thump function.
 * @returns {Promise} - Resolve when the thump function has completed, or when exit is true.
 */
function thump(thump, parameters, exit) {
  // Define log file path
  const LOG_FILE = '/tmp/myjob.log';

  // Open log file in append mode
  const logFile = fs.openSync(LOG_FILE, 'a');

  // Log execution command
  console.log(`Executing ${NODE_BIN} - ${CORE_DIR} - ${thump} - ${JSON.stringify(parameters)}`);

  // Execute thump function in detached process
  childProcess.spawn(NODE_BIN, [
    '-e',
    `require(${JSON.stringify(CORE_DIR)}).import('${thump}')(${parameters? `(${JSON.stringify(parameters)})` : ''}).catch(e => console.log(e)).then(() => process.exit())`
  ], {
    detached: true,
    stdio: [ 'ignore', logFile, logFile ]
  }).unref();

  // Exit current process if required
  if (exit!== false) {
    // Use async/await for clarity
    async function exitProcess() {
      try {
        await new Promise(resolve => {
          global.$ && global.$ && global.$done && global.$done();
          process.exit(0);
        });
      } catch (error) {
        // Handle error, e.g., log and continue
        console.error('Error exiting process:', error);
      }
    }
    exitProcess();
  }
}

// Export thump function
module.exports = thump;

This code defines a function thump that executes a Node.js script asynchronously.

Here's a breakdown:

  1. Setup:

  2. thump Function:

  3. Export:

In essence, this code provides a way to execute Node.js scripts asynchronously, passing parameters, logging output, and handling errors.