Search code examples
javascriptnode.jsmongodbmongoosemongoexport

Automating exports from a Node.js API to TSV or other excel compatible format


I built an application in the MEAN stack for querying and displaying a company's data. They use Power Query internally, so I'm trying to design an API endpoint that exports the results of a query to an Excel compatible format, such as TSV. I can do this easily using the mongoexport command line utility, however I'm having difficulties automating the use of this utility through my Node API. My current attempt at this follows, according to this tutorial:

var child = require('child-process');
var exec = child.exec();

 module.exports.tsvData = function (query) {
    //Atempted child process manipulation to use mongoexport CLI utility in this endpoint.
    var command = 'echo "ANDY"'

    child = exec(command, function (error, stdout, stderr) {
      sys.print('stdout: ' + stdout);
      sys.print('stderr: ' + stderr);
      if (error !== null) {
        console.log('exec error: ' + error);
      }
    });
  };

This returns the following error:

TypeError: object is not a function
at module.exports.tsvData (C:\Users\awimley\pstat\app_api\controllers\main.js:367:13)
at callbacks (C:\Users\awimley\pstat\node_modules\express\lib\router\index.js:164:37)
at param (C:\Users\awimley\pstat\node_modules\express\lib\router\index.js:138:11)
at pass (C:\Users\awimley\pstat\node_modules\express\lib\router\index.js:145:5)
at Router._dispatch (C:\Users\awimley\pstat\node_modules\express\lib\router\index.js:173:5)

This is on the child= line. I suspected this was because the tutorial was outdated, so I attempted using the syntax from the Child Process documents. I tried:

child = child_process.spawn('ls', {
    stdio: [
      0, // use parents stdin for child
      'pipe', // pipe child's stdout to parent
      fs.openSync('err.out', 'w') // direct child's stderr to a file
    ]
});

And it returns the following error:

    events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:1011:11)
    at Process.ChildProcess._handle.onexit (child_process.js:802:34)
19 Oct 09:18:44 - [nodemon] app crashed - waiting for file changes before starting...

Any assistance in firing a command line utility from a Node.js API would be fantastic.


Solution

  • I think there was a name collision, try this:

    var child_process = require('child_process');
    module.exports.tsvData = function(query) {
      var command = 'echo ANDY';
      var child = child_process.exec(command, function (error, stdout, stderr) {
        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);
        if (error !== null) {
          console.log('exec error: ' + error);
        }
      });
    };