1

So far I have the below code which I need to get the id from a JSON object:

var http = require("http");
var fs = require('fs');
//var bodyParser = require("body-parser");
//var moment = require("moment");

var options =  {
    "method" : "GET",
    "hostname" : "xxx.xxx.xxx.xxx",
    "port" : "18080",
    "path" : "/api/v1/applications/"
};

var req = http.request(options, function (res) {

    var chunks = [];

    res.on("data", function (chunk) {
        chunks.push(chunk);
    });

    res.on("end", function () {
        var body = JSON.parse(Buffer.concat(chunks));

        var arrFound = Object.keys(body).filter(function(key) {
            if (body[key].name.indexOf("TestName") > -1) {
                return body[key].name;
            }
        }).reduce(function(obj, key){
            obj = body[key].id;
            return obj;
        }, {});;
        //console.log("Name: ", arrFound);
        console.log("ID: ", arrFound);
    });
});

req.end();

I know it's reading the id as I currently write it out to the console(console.log("ID: ", arrFound);).

What I would like to do is have this available for use in other parts of my program. I assume I need to do something like encapsulate it in a function that I can call but node.js is new to me and I'm not entirely sure how/what to do.

Can anybody advise how to do this or point me to some resource that might help?

2
  • What code is it you want to reuse, this entire block or just the JSON parsing / filtering? Commented Jan 6, 2018 at 17:26
  • I just want to be able to get the id any time I need it Commented Jan 6, 2018 at 17:29

1 Answer 1

1

You should research the module pattern and exports. You are right, the basic idea is to export your code as a function. Based on how you've approached this, it should take a callback function. I've made a naive attempt with what you have.

Notice I pass a null as the first argument to the callback function. It is conventional when using callbacks in node to use the first argument for errors. You probably need some error handling.

Having said that, you night look into some libraries like requests, or the ES6 fetch function. These will allow you to organize your code more neatly. You'll probably wind up using promises instead of callbacks.

var http = require("http");
var fs = require('fs');
//var bodyParser = require("body-parser");
//var moment = require("moment");

var options =  {
    "method" : "GET",
    "hostname" : "xxx.xxx.xxx.xxx",
    "port" : "18080",
    "path" : "/api/v1/applications/"
};
exports.getId = function(callback) {
    var req = http.request(options, function (res) {

    var chunks = [];

    res.on("data", function (chunk) {
        chunks.push(chunk);
    });

    res.on("end", function () {
        var body = JSON.parse(Buffer.concat(chunks));

        var arrFound = Object.keys(body).filter(function(key) {
            if (body[key].name.indexOf("TestName") > -1) {
                return body[key].name;
            }
        }).reduce(function(obj, key){
            obj = body[key].id;
            return obj;
        }, {});;
        //console.log("Name: ", arrFound);
        callback(null, arrFound));
    });
});

    req.end();
}

You call it like this:

exports.getId(function(err, id){
    console.log(id)
})
Sign up to request clarification or add additional context in comments.

7 Comments

Callbacks are old school, have getId return a Promise instead so the calling code can make use of async / await.
I was doing the minimum with the code at have! If the asker looks into fetch they will be led to a promise based solution!
Thanks guys. I'll look into these. I think I have a bit of reading to do. I assumed I could run something like console.log(exports.getId()); but that throws "TypeError: callback is not a function:" am I missing something?
Having looked at thisi a little, am I correct in thinking I may be close with console.log(exports.getId()); but that I must pass some value. If so I'm not sure what that might be.
See the change.
|

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.