Spaniard89
Spaniard89

Reputation: 2419

Displaying the content of a variable on webpage in node.js

I have a code as follow:

app.get('/list', function(req, res) {
    serialport.list(function (err, ports) {
        ports.forEach(function(port) {
            var temp = port.manufacturer;
            console.log(temp);
            res.send(temp);
        });
    });
});

As it can be seen, port.manufacturer value is saved onto a variable temp and the resulting content of the temp is displayed onto console.

When I run the above code, i get something like this on my console:

Listening on port 3000...
Tinkerforge GmbH
GET /list 200 219ms - 16
Arduino (www.arduino.cc)
GET /favicon.ico 404 4ms 

But when I call the api http://localhost:3000/list,

Only Tinkerforge GnbH is displayed and not Arduino.

Is there something i am missing over here??

Do I have to save the list in a array or something??

Any help would be really appreciated.

Thanks a lot in advance. And BTW i am kinda begineer in both node.js and javascript.

Upvotes: 1

Views: 3173

Answers (1)

mekwall
mekwall

Reputation: 28974

The problem here is that .send, unlike .write, can be called only once. When called, Express will analyze the data and detect the correct headers (res.writeHead) to send before writing (res.write) to the socket and finally close the connection (res.close).

The solution is to either use .write or send all of your data in one go.

Using .write

app.get('/list', function(req, res) {
    serialport.list(function (err, ports) {
        ports.forEach(function(port) {
            var temp = port.manufacturer;
            res.write(temp);
        });
        res.send();
    });
});

Using .send

app.get('/list', function(req, res) {
    serialport.list(function (err, ports) {
        var manufacturers = [];
        ports.forEach(function (port) {
            manufacturers.push(port.manufacturer);
        });
        res.send(manufacturers.join(" "));
    });
});

I'd probably go with something like JSON.stringify(manufacturers) instead of using .join, since JSON is so easy to work with.

Upvotes: 2

Related Questions