why does console.log output all records and not response.end - Node.js -
im newbie node.js , i'm trying output data html. code works when use console.log not when use response.end. when use response.end see on record while when use console.log see records
see full code below:
var http = require('http'); var formoutput; var woocommerceapi = require('woocommerce-api'); // initialize woocommerceapi class var woocommerce = new woocommerceapi({ //url: 'http://example.com', // store url (required) }); function handlerequest(response) { // example woocommerce.get('products', function (err, data, res) { //console.log(res); //var fs = require('fs'); //var jsoncontent = json.parse(json.stringify(res, null, 4)) var jsoncontent = json.parse(res) (var = 0; < jsoncontent["products"].length; i++) { var name = jsoncontent["products"][i]; // works , can output records //console.log(name['title']); //console.log(name['id']); //console.log(name['sku']); //console.log(name['regular_price']); //response.writehead(200, { 'content-type': 'text/html' }); //res.end(name['id']); formoutput = name['regular_price']; //formoutput = '<h1>xyz repository commit monitor</h1>'; //response.write(); //only 1 record response.end(formoutput); //response.write('<html><head></head><body>'); //response.end("test"); //response.end('</body></html>'); } }); //response.end(formoutput); } http.createserver(function (req, response) { if (response.url === '/favicon.ico') { response.writehead(404); response.end(); } else { response.writehead(200, { 'content-type': 'text/html' }); } //code here... handlerequest(response); // response.end(formoutput); }).listen(1337, "localhost"); console.log("server running @ http://localhost:1337/");
with express, response.end() closes communication channel after 1 call 1 element sent user. don't use end() send data, in case, use response.json()
(or send()
) once after built data array.
var datatosend = []; (var = 0; < jsoncontent["products"].length; i++) { // build array of data send here } response.json(datatosend);
on side note, don't use response.end()
unless want end communication explicitly. response.json()
, response.send()
close channel when needed.
Comments
Post a Comment