简体   繁体   中英

Log images after successful http request using Node.js

I'm creating a script that will make a request 2 times per second to a localserver of cameras network and after it gets a positive response that camera detected someone I want to log three images.

In the json config file I have the triggerURL of the server, the interval port, the dataDir where logged images should be saved and a track array which contains the url of those images and the fileName they should receive.

This is the code of the script I use after reading the JSON file:

var configGet = {
    host: config.triggerURL
    , port: config.interval
    , method: 'GET'
};

setInterval(function () {
    var request = http.request(configGet, function (response) {
        var content = "";

        // Handle data chunks
        response.on('data', function (chunk) {
            content += chunk;
        });

        // Once we're done streaming the response, parse it as json.
        response.on('end', function () {
            var data = JSON.parse(response);

            if (data.track.length > 0) {
                //log images
                var download = function (uri, filename, callback) {
                    request.head(uri, function (err, res, body) {
                        request(uri)
                            .pipe(fs.createWriteStream(filename))
                            .on('close', callback);
                    });
                };
                for (var image in data.track) {
                    var path = config.dataDir + '/' + image.fileName
                    download(image.url, path.format(config.timestamp), function () {
                        console.log('done');
                    });
                }
            }
        });

        // Report errors
        request.on('error', function (error) {
            console.log("Error while calling endpoint.", error);
        });

        request.end();
    }, 500);
});

I have the following questions:

  1. This method produces some kind of error with the download process of the images.Can you identify it?

  2. Is there a better way of doing this process?

  1. Without running the code or deeper inspection; should not "data = JSON.parse(response)" rather be "data = JSON.parse(content)"? Also, if data is undefined or does not contain "track" the "if (data.track.length > 0)" will throw an error. This can be fixed with "if (data && data.track && data.track.length > 0)".
  2. I can not think of a very much better way. I would break it up more in functions to make the code more clear though.

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