Sunday, 12 March 2017

Mysql Order By VS. Node.js sort

I'm retrieving a list of rows from a mysql database and will need to sort the data. Is it less stress on my server to do the sort via mysql 'order by' clause, or to sort the data with node.js sort()? Which is more efficient?



via Justin Lok

How to only errors with winston module in Node.js

I have an application running on Node.js (server side) and I would like to only log errors based on an environment variable (For example : log_level=error node api.js) so this only logs errors on the console.

I have a log.js file that uses winston library

var fs = require("fs"),
  mkdirp = require("mkdirp"),
  path = require("path"),
  winston = require("winston");
  //const env = process.env.node_env || "development";

var filename = path.join(__dirname, "../app-debug.log");

//
// Remove the file, ignoring any errors
//
try {
  fs.unlinkSync(filename);
} catch (ex) {}

var logger = new(winston.Logger)({
  levels: {
    trace: 0,
    input: 1,
    verbose: 2,
    error: 3,
    debug: 4,
    info: 5,
    data: 6,
    help: 7,
    warn: 8
  },
  colors: {
    trace: "magenta",
    input: "grey",
    verbose: "cyan",
    prompt: "red",
    error: "blue",
    info: "green",
    data: "grey",
    help: "cyan",
    warn: "yellow"
  },
  transports: [
    new(winston.transports.Console)({
      prettyPrint: true,
      colorize: true,
      silent: false,
      timestamp: true,
      level: "error"
    }),
    new(winston.transports.File)({
      filename: filename
    })
  ]
});

module.exports = logger;

This file is in my root directory,What is happening now is that all log levels are printed in my console.What am I doing wrong? Any help?



via Rawan Hamdi

Randomly disconnecting from MongoDB. Using MEAN stack

im having this weird problem. It just randomly im getting disconnected to MongoDB from my NodeJS server. This happens when i try to change something on the angular side or server code, it doesn't always disconnect, it's just sometimes.

enter image description here

do any of you experience this problem? thank you!



via John

Nodejs and npm module offline installation

I work in company that has some corporate proxy. I am able to install nodejs but I cannot install any npm module at all. I tried alot things, different proxy settings but none of them worked. Nodejs simply can't connect to internet to fetch modules I need. Basically Im trying to setup Cordova and Ionic on this computer.

I was wondering if there any way to offline install it? I meant, is there any way to bring these files in USB drive or something and then install it?

It is possible or not?

Thank you Guys :)



via Amrit Sohal

node async module: combine parallel with retry

Here's a simple example of the use of async.parallel:

var fakeTimer = 0;
async.parallel({
    one: function(callback) {
        if (fakeTimer < 2) {
            callback(new Error('too soon!'), null);
            fakeTimer++;
        } else {
            callback(null, 'I am one');
        }
    },
    two: function(callback) {
        callback(null, 'I am two');
    }
}, function(err, results) {
    if (err) {
        console.log('failed!');
    } else {
        console.log(results);
    }
});

When this runs, of course it always ends in failure. What I'd like to do is keep retrying until fakeTimer has become large enough that the one function succeeds.

So either the whole async.parallel could be retried e.g. 5 times, or just the one function. I know that there is the async.retry feature, but I just can't get my head around how to combine that with async.parallel to achieve what I want.

I think ideally the whole async.parallel should be retried, so that it works if the error happens in any of the parallel branches, but it would be great to see an example of an overall retry and a per-branch retry.



via drmrbrewer

elasticsearch - count items after post

I'm using elasticsearch client for node js (working with elastic 2.x), and I want to avoid the exception that is thrown when the maximum number of documents allowed per index is exceeded. I could not find the name of the exception anywhere, so if possible, I would like to get the number of documents in the index at the same query where I POST data to db. Otherwise I will need to run a separate count query before or after each POST. Any type of solution will be appreciated.



via Mister_L

Client side can not take the json data

I have a nodejs server and the code that I have as below. I send an AJAX request and I want the server to send me a response of a json data. When I put res.write()("string data like hello hello") in the server code, client side can take the value of inside and I can see the value on the console. But I cannot get json value with this function. I tried res.end() and res.send() functions as well but it didn't work. How can I send the json value and the following client side code can take the value correctly?

Server side,

app.use('/', function(req, res) {
console.log("req body app use", req.body);
var str= req.path;

if(str.localeCompare(controlPathDatabaseLoad) == 0)
{
    console.log("controlPathDatabaseLoad");
    mongoDbHandleLoad(req, res);
    res.writeHead('Content-Type', 'application/json');
    res.write("Everything all right with database loading"); //I can get this message
    //res.end(json) I can not get json message with this function as well
    res.send("OK");
    //res.send(JSON.stringify(responseBody)); I can not get json message
}

Client side,

function loadDatabaseData()
    {
        console.log("loadDatabaseData");
        var oReq = new XMLHttpRequest();
        oReq.open("GET", "http://192.168.80.143:2800/load", true);
        oReq.setRequestHeader("Content-type", "application/json;charset=UTF-8");
        oReq.onreadystatechange = function() {//Call a function when the state changes.
            if(oReq.readyState == 4 && oReq.status == 200) {
                console.log("http response", oReq.response);
                console.log("http responseText", oReq.responseText);
            }
        }
        oReq.send();

    }



via zoint