Harrison Cramer
Harrison Cramer

Reputation: 4506

Combining Synchronous Python w/ NodeJS

I have a node script that looks like this:

// Preset Modules...
const fs = require("fs-extra");
const path = require("path");
const { join } = path;
const axios = require("axios");

// Global/Multi modules...
const { today } = require("./keys/globals");
const { logger } = require("./logger");

// Sequence modules...
const downloader = require("./downloader");
const settingScraper = require("./settings");
const treeMaker = require("./treeMaker");
/****/ const pythonWriter = require("./pythonWriter"); /****/
const fbDaemon = require("./firebase");
const zipper = require("./zipper");
const mailer = require("./mailer");
const { success, failure } = require("./results");

logger.write(`\nStarting download for: ${today}, at ${Date.now()}`);

axios.get(`http://federalregister.gov/api/v1/public-inspection-documents.json?conditions%5Bavailable_on%5D=${today}`)
  .then(downloader)
  .then(settingScraper)
  .then(treeMaker)
/****/  .then(pythonWriter) /****/
  .then(fbDaemon) // Should pass down array structure, like in config file.
  .then(zipper)
  .then(mailer)
  .then(success)
  .catch(failure);

The function downloads a number of files from an API online, and the pythonWriter is a separate module. Within that module I would like to trigger a python script, which would "pause" or execute synchronously, before they pythonWriter returned a promise. The promise wouldn't have to contain any data.

Look something like this:

const util = require("util");
const spawn = require("child_process").spawn;

const pythonWriter = () => {
  const process = spawn("python", ["./script.py"]);
}

module.exports = pythonWriter;

How can I spawn or create a sub-process that executes synchronously before the rest of my Javascript code? Or, if that's not possible, return a promise-like object that would then trigger a separate then-block?

Thanks for your help.

Upvotes: 0

Views: 289

Answers (1)

jfriend00
jfriend00

Reputation: 707696

Have you looked at the child_process documentation?

You can either use spawnSync() or you can watch for events on the childProcess object returned by spawn to know when its done or you can use the callback function with .exec() or .execFile() or .spawn() to see when they are done.

It seems that what you're asking is already covered in the child_process doc.

Here's an example using .spawn() taken from the doc:

const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

You could listen for the close event to see when it's done.

Upvotes: 1

Related Questions