2

I'm working on a school assignment, Node.js, and have trouble with getting my output correct. It's the res.end part that isn't working, but res.end(stdout); works. Why?

case "/status":
    /**
     * Run child process "uname -a".
     */
    cp.exec("uname -a", (error, stdout, stderr) => {
        if (error || stderr) {
            // Do something with the error(s)
            console.log("Something went wrong...", error, stderr);
        }

        // status route
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end({
            "uname": stdout
        });
    });
break;
2
  • @JoeClay, send is not a function in non-Express.js. Commented Mar 2, 2017 at 13:14
  • Oops, I'm so used to using Express that I didn't realize, my apologies! The answer may still be similar, however - I'll write one up and post it. Commented Mar 2, 2017 at 13:17

1 Answer 1

1

As specified in the Node.js docs, res.end can only take a string or a buffer - or nothing at all - as its first parameter. If you wish to send JSON using it, you'll have to set the content type (which you've done) and stringify the object:

res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({
    "uname": stdout
}));

This is effectively what Express.js does when you call res.send/res.json on an object.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help! I never tried putting JSON.stringify there.
@AnttiKeränen: No problem! I think something key to bear in mind when working with Node's HTTP module is that it's a web server API, not a web application API. They don't implement higher level concerns like JSON, or authentication, etc. etc. etc. - they leave it up to you (or more likely, a framework like Express, Hapi or Restify) to decide how to implement those features in a way that fits your needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.