0

I have a node.js and express script that is taking a file, running a script on it, and returning stdout to the console log. Instead of logging the stdout to the console, i would like to send the output (which is in JSON) back to the client in a response. I'm seeing that maybe res.send is the proper way to do this. Is this the correct method and where would this go in my code?

const multer = require('multer')
const fs = require('fs')
const exec = require('child_process').exec
const express = require('express')

var app = express();

const upload = multer({
    dest: './upload',
    fileFilter: function (req, file, cb) {
        if (file.mimetype != 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
            return cb(new Error('Wrong file type'))
        }
        cb(null,true)
    }
}).single('file');

app.post('/upload', upload, function(req, res) {

  const filePath = req.file.path
  exec(`./script.sh ${filePath}`,
      function (error, stdout, stderr) {
          console.log(stdout);
          if (error !== null) {
              console.log('exec error: ' + error);
          }
          res.setHeader('Content-Type', 'application/json');
          res.send(JSON.stringify({ test: 'test' }));
      });
});
Hysii
  • 702
  • 2
  • 10
  • 23

1 Answers1

3

Generaly, one way is:

res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ a: 1 }));

But since Express.js 3x the response object has a json() method which sets all the headers correctly for you and returns the response in JSON format.

Example:

 res.json({"foo": "bar"});

As a reference to here: Proper way to return JSON using node or Express

In your case, you can try something like this:

app.post('/upload', upload, function(req, res) {

const filePath = req.file.path
exec(`./script.sh ${filePath}`,
    function (error, stdout, stderr) {
      if (error !== null) {
          console.log('exec error: ' + error);
      } 
      res.json(stdout);
  });
});
user2212726
  • 1,225
  • 3
  • 16
  • 23
  • Refer to what i have done above, as i just made an edit. I have also tried the way you suggested. Both add nothing new to my response. I am viewing via the console in my browser and each response looks the exact same, and doesnt include what i am attempting to add. – Hysii Jul 25 '18 at 18:53
  • If this is your whole code, it seems like you miss the initialisation of the express server something like: const express = require('express'); const app = express(); try this tutorial and advance from there: https://expressjs.com/en/starter/hello-world.html – user2212726 Jul 25 '18 at 19:00
  • didnt miss it. Its up top – Hysii Jul 25 '18 at 19:03
  • look again, as i see you only required it: const app = require('express') but what need to be done: const express = require('express') const app = express(); -- but hey maybe i'm wrong and the server is up, and that way i don't understand why the res.json doesn't work for you. – user2212726 Jul 25 '18 at 19:04
  • edited accordingly....wasnt missing from my code, just from the post....the problem still persists – Hysii Jul 25 '18 at 19:07
  • try this: res.status(200).json({"foo": "bar"}); == maybe surrond it with a try,catch and see if an error thrown. – user2212726 Jul 25 '18 at 19:09
  • does the "console.log(stdout);" works? if so, does "res" even exist in that scope? maybe 'res' is undefined? try to return something as i suggested without the exec function and callback and see, maybe 'res' isn't pass into exec as you expected. – user2212726 Jul 25 '18 at 19:14
  • i guess this is it, try to put it inside a promise and resolve it on success, your promise .then should do the res.status(200).json(stdout) from the scope of app.post. – user2212726 Jul 25 '18 at 19:26