1

I have a python interactive script that talks with my 3D printer. If I open this script, I type two commands that outputs information to stdout:

  1. connect to the printer (USB) at 250000 bauds
  2. Get the temperature

I would like the connection with the printer to remain permanently, because in the future, I may connect again to the script to poll for the ETA of the current print job.

Then, NodeJS with Express allows me to create a simple web API that communicates with this script using a child process, but I am getting a lot of errors.

My code:

var express = require('express');
var app = express();
var child_process = require('child_process');
spawn = child_process.spawn;

var n = child_process.spawn('/home/pi/virtualenvs/printrun/bin/python', ['-i','-u','/home/pi/projects/printrun/Printrun/pronsole.py']);
n.stdin.write('connect /dev/ttyACM0 250000');
n.stdin.write('\n');

app.get('/printer_temp', function (req, res) {
        n.stdin.write('gettemp');
        n.stdin.write('\n');

        n.stdout.on('data', function(data){
                res.json({printer_status: data});   //I should get kind of like an "OK", with a bunch of other lines.
        });

});


var server = app.listen(3000, function () {
        var host = server.address().address;
        var port = server.address().port;
        console.log('Starting server');
});

I'm getting errors line 29: Error: Can't set headers after they are sent.

What am I doing wrong?

Axel
  • 457
  • 9
  • 20
  • what is line 29? and why do you want to write your server in js when you can have py do it? – taesu Sep 10 '15 at 12:41
  • Line 29 is res.json({printer_status: data}); I'm using js because node+express is the easiest lightiest way to have a rest API. I have also considered using Flask, but I'm not sure. What would you recommend? – Axel Sep 10 '15 at 12:55
  • Django or Flask. your error is [duplicate](http://stackoverflow.com/questions/7042340/node-js-error-cant-set-headers-after-they-are-sent?answertab=active#tab-top) anyways – taesu Sep 10 '15 at 12:59
  • I saw this post earlier, but I think it may not my case. As the stdout of the python script comes, the event 'data' is triggered more than once, and there is the problem. I want to output all the stdout at once. – Axel Sep 10 '15 at 14:22

1 Answers1

0

This is express telling you that it is unable to modify the contents of the HTTP header after it has been sent to the client. At some point your system is trying to do something to the header, express is explaining that it can't get to it. The problem most likely not in the code above.

I fought this for a couple of days. One difficult thing to master with Node is the way event's are processed and WHEN you can do things.

Please see this question (255 upvotes so you aren't alone) and it should be clear: Error: Can't set headers after they are sent to the client

Community
  • 1
  • 1