Hysii
Hysii

Reputation: 772

Returning json from node back to client

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' }));
      });
});

Upvotes: 0

Views: 7759

Answers (1)

user2212726
user2212726

Reputation: 1285

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);
  });
});

Upvotes: 3

Related Questions