简体   繁体   中英

NodeJS with Express and python interactive script

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM