Sunday 19 March 2017

How to fire an event when something changes in database to clients in web server using node js

I want to send a notification to the connected clients of my webserver when value changes in mongo database using node js . Just like firebase database does. What's the mechanism of such approach?



via Abdalltif Basher

Sequelize: How to enable onDelete: cascade?

Sequelize Version: 3.24.3

I'm trying to enable cascade deletion on an association in Sequelize.

My data model looks like:

// models/pin.js
Pin.belongsTo(models.category, { foreignKey: 'categoryId' });

// models/category.js
Category.hasMany(models.pin, { foreignKey: 'categoryId' });

I've tried every permutation of adding onDelete: 'cascade, hooks:true to just the belongsTo options, just the hasMany options, and then both options.

This post suggested just adding those flags to the belongsTo association (the docs suggest adding it to the hasMany). When I trigger a delete, I'm receiving the foreign key constraint error:

SequelizeForeignKeyConstraintError: update or delete on table "categories" violates foreign key constraint "pins_category_id_fkey" on table "pins"



via kuiro5

Electron — Can't get custom icon to appear

I'm having an issue setting the icon for my Electron app in two different ways:

Non-Packaged (Running the app via terminal)

My main.js does specify an 'icon' value, pointing to the icon file, but it does not apply.

Packaged (with electron-packager)

My package.json file specifies the 'icon' key, pointing to the icon file, and I have the .icns (Mac) file in the build directory. I used electron-packager to build the app, but the icon is not applied, the default electron icon is used instead.

Not sure what I'm doing wrong here, everything appears correct.



via Karric

How i can use FileSaver.js module without Node.Js?

i have visited a github code to increase effort for saving a file from javascript/html. We have some problem with to use it, because it mae for node.js. I'v found some demo.js code to save the file from demo.html itself. But, it is useless because i unfortunatly can't edit, because i wonder it just for demo.html class, and it will become crash if i make a reference to another html file.

This is the code File Saver.js

/* FileSaver.js  * A saveAs() FileSaver implementation.  * 1.3.2  * 2016-06-16 18:25:19  *  * By Eli Grey, http://eligrey.com  * License: MIT  *   See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md  */

/*global self */ /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */

/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js
*/

var saveAs = saveAs || (function(view) {    "use strict";   // IE <10 is explicitly unsupported     if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {      return;     }   var
          doc = view.document
          // only get URL when necessary in case Blob.js hasn't overridden it yet       , get_URL = function() {            return view.URL || view.webkitURL || view;      }       , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")      , can_use_save_link = "download" in save_link       , click = function(node) {          var event = new MouseEvent("click");            node.dispatchEvent(event);      }       , is_safari = /constructor/i.test(view.HTMLElement) || view.safari      , is_chrome_ios
=/CriOS\/[\d]+/.test(navigator.userAgent)       , throw_outside = function(ex) {            (view.setImmediate || view.setTimeout)(function() {
                throw ex;           }, 0);      }       , force_saveable_type = "application/octet-stream"      // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to         , arbitrary_revoke_timeout = 1000 * 40 // in ms         , revoke = function(file) {             var revoker = function() {
                if (typeof file === "string") { // file is an object URL
                    get_URL().revokeObjectURL(file);
                } else { // file is a File
                    file.remove();
                }           };          setTimeout(revoker, arbitrary_revoke_timeout);      }       , dispatch = function(filesaver, event_types, event) {          event_types = [].concat(event_types);           var i = event_types.length;             while (i--) {
                var listener = filesaver["on" + event_types[i]];
                if (typeof listener === "function") {
                    try {
                        listener.call(filesaver, event || filesaver);
                    } catch (ex) {
                        throw_outside(ex);
                    }
                }           }       }       , auto_bom = function(blob) {           // prepend BOM for UTF-8 XML and text/* types (including HTML)          // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF          if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
                return new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});            }           return blob;        }       , FileSaver = function(blob, name, no_auto_bom) {           if (!no_auto_bom) {
                blob = auto_bom(blob);          }           // First try a.download, then web filesystem, then object URLs          var
                  filesaver = this
                , type = blob.type
                , force = type === force_saveable_type
                , object_url
                , dispatch_all = function() {
                    dispatch(filesaver, "writestart progress write writeend".split(" "));
                }
                // on any filesys errors revert to saving with object URLs
                , fs_error = function() {
                    if ((is_chrome_ios || (force && is_safari)) && view.FileReader) {
                        // Safari doesn't allow downloading of blob urls
                        var reader = new FileReader();
                        reader.onloadend = function() {
                            var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
                            var popup = view.open(url, '_blank');
                            if(!popup) view.location.href = url;
                            url=undefined; // release reference before dispatching
                            filesaver.readyState = filesaver.DONE;
                            dispatch_all();
                        };
                        reader.readAsDataURL(blob);
                        filesaver.readyState = filesaver.INIT;
                        return;
                    }
                    // don't create more object URLs than needed
                    if (!object_url) {
                        object_url = get_URL().createObjectURL(blob);
                    }
                    if (force) {
                        view.location.href = object_url;
                    } else {
                        var opened = view.open(object_url, "_blank");
                        if (!opened) {
                            // Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
                            view.location.href = object_url;
                        }
                    }
                    filesaver.readyState = filesaver.DONE;
                    dispatch_all();
                    revoke(object_url);
                }           ;           filesaver.readyState = filesaver.INIT;

            if (can_use_save_link) {
                object_url = get_URL().createObjectURL(blob);
                setTimeout(function() {
                    save_link.href = object_url;
                    save_link.download = name;
                    click(save_link);
                    dispatch_all();
                    revoke(object_url);
                    filesaver.readyState = filesaver.DONE;
                });
                return;             }

            fs_error();         }       , FS_proto = FileSaver.prototype        , saveAs = function(blob, name, no_auto_bom) {          return new FileSaver(blob, name || blob.name || "download", no_auto_bom);       }   ;   // IE 10+ (native saveAs)   if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {       return function(blob, name, no_auto_bom) {          name = name || blob.name || "download";

            if (!no_auto_bom) {
                blob = auto_bom(blob);          }           return navigator.msSaveOrOpenBlob(blob, name);      };  }

    FS_proto.abort = function(){};  FS_proto.readyState = FS_proto.INIT = 0;    FS_proto.WRITING = 1;   FS_proto.DONE = 2;

    FS_proto.error =    FS_proto.onwritestart =     FS_proto.onprogress =   FS_proto.onwrite =  FS_proto.onabort =  FS_proto.onerror =  FS_proto.onwriteend =       null;

    return saveAs; }(
       typeof self !== "undefined" && self  || typeof window !== "undefined" && window  || this.content )); // `self` is undefined in Firefox for Android content script context // while `this` is nsIContentFrameMessageManager // with an attribute `content` that corresponds to the window

if (typeof module !== "undefined" && module.exports) {   module.exports.saveAs = saveAs; } else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) {   define("FileSaver.js", function() {
    return saveAs;   }); }

And the demo.js

/*! FileSaver.js demo script
 *  2016-05-26
 *
 *  By Eli Grey, http://eligrey.com
 *  License: MIT
 *    See LICENSE.md
 */

/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/demo/demo.js */

/*jshint laxbreak: true, laxcomma: true, smarttabs: true*/
/*global saveAs, self*/

(function(view) {
"use strict";
// The canvas drawing portion of the demo is based off the demo at
// http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/
var
      document = view.document
    , $ = function(id) {
        return document.getElementById(id);
    }
    , session = view.sessionStorage
    // only get URL when necessary in case Blob.js hasn't defined it yet
    , get_blob = function() {
        return view.Blob;
    }

    , canvas = $("canvas")
    , canvas_options_form = $("canvas-options")
    , canvas_filename = $("canvas-filename")
    , canvas_clear_button = $("canvas-clear")

    , text = $("text")
    , text_options_form = $("text-options")
    , text_filename = $("text-filename")

    , html = $("html")
    , html_options_form = $("html-options")
    , html_filename = $("html-filename")

    , ctx = canvas.getContext("2d")
    , drawing = false
    , x_points = session.x_points || []
    , y_points = session.y_points || []
    , drag_points = session.drag_points || []
    , add_point = function(x, y, dragging) {
        x_points.push(x);
        y_points.push(y);
        drag_points.push(dragging);
    }
    , draw = function(){
        canvas.width = canvas.width;
        ctx.lineWidth = 6;
        ctx.lineJoin = "round";
        ctx.strokeStyle = "#000000";
        var
              i = 0
            , len = x_points.length
        ;
        for(; i < len; i++) {
            ctx.beginPath();
            if (i && drag_points[i]) {
                ctx.moveTo(x_points[i-1], y_points[i-1]);
            } else {
                ctx.moveTo(x_points[i]-1, y_points[i]);
            }
            ctx.lineTo(x_points[i], y_points[i]);
            ctx.closePath();
            ctx.stroke();
        }
    }
    , stop_drawing = function() {
        drawing = false;
    }

    // Title guesser and document creator available at https://gist.github.com/1059648
    , guess_title = function(doc) {
        var
              h = "h6 h5 h4 h3 h2 h1".split(" ")
            , i = h.length
            , headers
            , header_text
        ;
        while (i--) {
            headers = doc.getElementsByTagName(h[i]);
            for (var j = 0, len = headers.length; j < len; j++) {
                header_text = headers[j].textContent.trim();
                if (header_text) {
                    return header_text;
                }
            }
        }
    }
    , doc_impl = document.implementation
    , create_html_doc = function(html) {
        var
              dt = doc_impl.createDocumentType('html', null, null)
            , doc = doc_impl.createDocument("http://www.w3.org/1999/xhtml", "html", dt)
            , doc_el = doc.documentElement
            , head = doc_el.appendChild(doc.createElement("head"))
            , charset_meta = head.appendChild(doc.createElement("meta"))
            , title = head.appendChild(doc.createElement("title"))
            , body = doc_el.appendChild(doc.createElement("body"))
            , i = 0
            , len = html.childNodes.length
        ;
        charset_meta.setAttribute("charset", html.ownerDocument.characterSet);
        for (; i < len; i++) {
            body.appendChild(doc.importNode(html.childNodes.item(i), true));
        }
        var title_text = guess_title(doc);
        if (title_text) {
            title.appendChild(doc.createTextNode(title_text));
        }
        return doc;
    }
;
canvas.width = 500;
canvas.height = 300;

  if (typeof x_points === "string") {
    x_points = JSON.parse(x_points);
} if (typeof y_points === "string") {
    y_points = JSON.parse(y_points);
} if (typeof drag_points === "string") {
    drag_points = JSON.parse(drag_points);
} if (session.canvas_filename) {
    canvas_filename.value = session.canvas_filename;
} if (session.text) {
    text.value = session.text;
} if (session.text_filename) {
    text_filename.value = session.text_filename;
} if (session.html) {
    html.innerHTML = session.html;
} if (session.html_filename) {
    html_filename.value = session.html_filename;
}

drawing = true;
draw();
drawing = false;

canvas_clear_button.addEventListener("click", function() {
    canvas.width = canvas.width;
    x_points.length =
    y_points.length =
    drag_points.length =
        0;
}, false);
canvas.addEventListener("mousedown", function(event) {
    event.preventDefault();
    drawing = true;
    add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, false);
    draw();
}, false);
canvas.addEventListener("mousemove", function(event) {
    if (drawing) {
        add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, true);
        draw();
    }
}, false);
canvas.addEventListener("mouseup", stop_drawing, false);
canvas.addEventListener("mouseout", stop_drawing, false);

canvas_options_form.addEventListener("submit", function(event) {
    event.preventDefault();
    canvas.toBlobHD(function(blob) {
        saveAs(
              blob
            , (canvas_filename.value || canvas_filename.placeholder) + ".png"
        );
    }, "image/png");
}, false);

text_options_form.addEventListener("submit", function(event) {
    event.preventDefault();
    var BB = get_blob();
    saveAs(
          new BB(
              [text.value || text.placeholder]
            , {type: "text/plain;charset=" + document.characterSet}
        )
        , (text_filename.value || text_filename.placeholder) + ".txt"
    );
}, false);

html_options_form.addEventListener("submit", function(event) {
    event.preventDefault();
    var
          BB = get_blob()
        , xml_serializer = new XMLSerializer()
        , doc = create_html_doc(html)
    ;
    saveAs(
          new BB(
              [xml_serializer.serializeToString(doc)]
            , {type: "application/xhtml+xml;charset=" + document.characterSet}
        )
        , (html_filename.value || html_filename.placeholder) + ".xhtml"
    );
}, false);

view.addEventListener("unload", function() {
    session.x_points = JSON.stringify(x_points);
    session.y_points = JSON.stringify(y_points);
    session.drag_points = JSON.stringify(drag_points);
    session.canvas_filename = canvas_filename.value;

    session.text = text.value;
    session.text_filename = text_filename.value;

    session.html = html.innerHTML;
    session.html_filename = html_filename.value;
}, false);
}(self));

The html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US-x-Hixie">
<head>
    <meta charset="utf-8"/>
    <title>FileSaver.js demo</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/eligrey/FileSaver.js/702cd2e820b680f88a0f299e33085c196806fc52/demo/demo.css"/>
</head>
<body>
    <h1><a href="https://github.com/eligrey/FileSaver.js">FileSaver.js</a> demo</h1>
    <p>
        The following examples demonstrate how it is possible to generate and save any type of data right in the browser using the <code>saveAs()</code> FileSaver interface, without contacting any servers.
    </p>
    <section id="image-demo">
        <h2>Saving an image</h2>
        <canvas class="input" id="canvas" width="500" height="300"/>
        <form id="canvas-options">
            <label>Filename: <input type="text" class="filename" id="canvas-filename" placeholder="doodle"/>.png</label>
            <input type="submit" value="Save"/>
            <input type="button" id="canvas-clear" value="Clear"/>
        </form>
    </section>
    <section id="text-demo">
        <h2>Saving text</h2>
        <textarea class="input" id="text" placeholder="Once upon a time..."/>
        <form id="text-options">
            <label>Filename: <input type="text" class="filename" id="text-filename" placeholder="a plain document"/>.txt</label>
            <input type="submit" value="Save"/>
        </form>
    </section>
    <section id="html-demo">
        <h2>Saving rich text</h2>
        <div class="input" id="html" contenteditable="">
            <h3>Some example rich text</h3>
            <ul>
                <li><del>Plain</del> <ins>Boring</ins> text.</li>
                <li><em>Emphasized text!</em></li>
                <li><strong>Strong text!</strong></li>
                <li>
                    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="70" height="70">
                        <circle cx="35" cy="35" r="35" fill="red"/>
                        <text x="10" y="40">image</text>
                    </svg>
                </li>
                <li><a href="https://github.com/eligrey/FileSaver.js">A link.</a></li>
            </ul>
        </div>
        <form id="html-options">
            <label>Filename: <input type="text" class="filename" id="html-filename" placeholder="a rich document"/>.xhtml</label>
            <input type="submit" value="Save"/>
        </form>
    </section>
    <script async="" src="https://cdn.rawgit.com/eligrey/Blob.js/0cef2746414269b16834878a8abc52eb9d53e6bd/Blob.js"/>
    <script async="" src="https://cdn.rawgit.com/eligrey/canvas-toBlob.js/f1a01896135ab378aa5c0118eadd81da55e698d8/canvas-toBlob.js"/>
    <script async="" src="https://cdn.rawgit.com/eligrey/FileSaver.js/e9d941381475b5df8b7d7691013401e171014e89/FileSaver.min.js"/>
    <script async="" src="https://cdn.rawgit.com/eligrey/FileSaver.js/597b6cd0207ce408a6d34890b5b2826b13450714/demo/demo.js"/>
</body>
</html>



via Ilham Jang Jaya Putra

Node JS EJS get URL parameters

I'm trying to read URL parameters in an EJS template, however everything I try or read from google isn't working. Here's the relevant part of my app.js file:

app.post('/account/logintoaccount', function(req, res) {
    var email = req.body.email;
    if(email === '') {
        res.redirect('https://myurl.com/account/login?e=bademail');
        return;
    }
    var password = req.body.password;
    if(password === '') {
        res.redirect('https://myurl.com/account/login?e=badpassword');
        return;
    }
    res.redirect('https://myurl.com/?email=' + email + '&pw=' + password);
});

And here's where I'm trying to display the variable in my EJS file:

<div id="title-text">
    <% if(!req.query.e) { %>
        <p>Log into your account:</p>
    <% } else if(req.query.e === "badpass") { %>
        <div class="alert alert-danger"><strong>Error</strong> incorrect password</div>
    <% } else if(req.query.e === "bademail") { %>
        <div class="alert alert-danger"><strong>Error</strong> unknown email address</div>
    <% } %>
</div>

If I remove this part of my EJS file my redirects work fine. The URL has the parameters in it and all is good. However whenever I try and use my URL parameters in any way shape or form in my EJS file it breaks and gives me an "X is undefined error". I've tried using 'e', 'req.query.e', 'this.e', 'this.req.query.e' and anything else that google results have suggested I do.

My end goal is to be able to read the URL parameters in https://myurl.com/account/login?e=somethinghere

Then check what 'e' holds. I've spent the last 30+ minutes reading over google results however I believe they're either outdated or I'm just doing them wrong. Can anyone help please? Thank you for your time



via GatorFlores

Patterns for managing user profiles in nodejs/react?

Not talking about authentication -- there are plenty of options for that like passport or auth0. But in node and/or React, what do we do with the rest of the user profile and related user data we collect? Things like application preferences or links to a users social profiles or phone number, etc etc.

Is the only option just to store that user profile data in a database like its 1995 or is there a handy module/library/tool people recommend that makes it easier?



via scottsanchez

Mongoose schema and find cannot populate

I have the following schema:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.Promise = global.Promise;

var userSkillSchema = Schema ({
    email:{type:String, required:true, ref:'User'},
    skill:{type:String, required:true},
    sub1:{type:String, required:true},
    sub2:{type:String, required:true},
    experience:{type:Number, required:true}
});

var UserSkill = mongoose.model('UserSkill',userSkillSchema);
module.exports = UserSkill;

When I am doing a simple UserSkill.find as follow:

router.get('/getskill/:email', function(req, res){
    UserSkill.find({email:req.params.email})
    .populate('email')
    .exec(function(err, userskill){
        if (err) return res.send(err);
        else{
            res.json({userskill});
        }
    });
});

I am getting the following error:

{
  "message": "Cast to ObjectId failed for value \"john@gmail.com\" at path \"_id\" for model \"UserSkill\"",
  "name": "CastError",
  "stringValue": "\"JohnDoe@gmail.com\"",
  "kind": "ObjectId",
  "value": "JohnDoe@gmail.com",
  "path":

In the documentation it is written that I can use String, Number, ObjectId, Buffer as Ref. Which I did. But still I am getting errors.



via user3450754

Node Promise and AWS Lambda error handling

I am doing some error handling in my node Lambda, using native promises. For some reason, my promise.reject never triggers. I am specifically sending in a bad url to get it to fail, yet AWS sends back 502 "Bad Gateway". This is presumably the way AWS handles internal server issues, which is fine, but I want to send back the reject reason. What am I doing wrong?

Promise

function parseData(data) {
    url = 'https://notarealurl';

    return new Promise((resolve, reject) => {
        https.get(url, (res) => {
            let body = '';
            res.on('data', (chunk) => {
                body += chunk;
            })
            .on('end', () => {
                resolve(body);
            })
            //this reject will trigger when there is an error with the request
            .on('error', (err) => {
                const rejectReason = {
                    statusCode: 500,
                    body: 'Internal Server Error: ' + err
                };
                reject(rejectReason)
            });
        })
    });
}

my handler:

function handler(event, context) {
    parseData(event.queryStringParameters)
    .then((result) => {
        const parsed = JSON.parse(result);
        //handle error message returned in response
        if (parsed.error) {
            const oAuthError = 'Authentication Error';
            let error = {
                headers: {"Content-Type": "application/json"},
                body: JSON.stringify(parsed.error)
            };
            if(parsed.error.type === oAuthError) {
                error.statusCode = 401;
                context.succeed(error);
            } else {
                error.statusCode = 404;
                return context.succeed(error);
            }
        } else {
            return context.succeed({
                statusCode: 302,
                headers: "Success"
              });
        }
    })
    .catch((reason) => {
        console.log('Promise rejected!!!!', reason)
    })
}

What is the AWS error coming out instead of my promise.reject errorReason?



via jmcgui05

express.js 4 has broken request.on('data') triggering

I'm hoping someone can either find what I'm doing wrong or can verify what I'm discovering to be true.

On a post to a node.js server there just isn't any way in the world request.on('data') works. Body-parser/json just isn't setting up express correctly or express isn't doing it's job, or both.

Following are two paired projects, one server & one client to send a post to the server. Both are in node.js. The server includes express & body-parser

This is server side:

/* Used to start Node
var debug = require('debug')('ExpressApp1');
var app = require('../app');

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function() {
    debug('Express server listening on port ' + server.address().port);
});
*/

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

var fRawBody = function (req, res, buf, encoding) {
    if (buf && buf.length) {
        req.rawBody = buf.toString(encoding || 'utf8');
        console.log("buf", req.rawBody);
    }
}

app.use('/', bodyParser.json({ verify: fRawBody }));

app.use('/', function (req, res, next) {
    var data = '';
    req.on('data', function (chunk) {
        console.log('data');
        data += chunk;
    });
    req.on('end', function () {
        req.rawBody = data;
        console.log("raw", req.rawBody);
    });
    res.sendStatus(200);
});


module.exports = app;

--- end of app.js ----

This is the client.

Client side response.on('data') works fine.

var http = require("http");

var options = {
    "method": "POST",
    "hostname": "127.0.0.1",
    "port": "1337",
    "path": "/",
    "headers": {
        "content-type": "application/json",
        "cache-control": "no-cache",
        "postman-token": "44e8850a-7a9d-42ce-fbbf-02ac3e6e051b"
    }
};

var req = http.request(options, function (res) {
    var chunks = [];

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

    res.on("end", function () {
        var body = Buffer.concat(chunks);
        console.log(body.toString());
    });
});

req.write(JSON.stringify({ data: { theGreatest: 'SMT' } }));
req.end();

I'm hoping someone can either find what I'm doing wrong or can verify what I'm finding out to be true.

Node.js 4.2.4 (client & server)

Express 4.9.8 (server)

Body-Parser.js 1.8.4 (server)

Thanks.



via user2367083

jQuery getJSON fails with 404 error

The URL that the getJSON request is sent to definitely exists, but the request fails with a 404 error. The URL just hosts a JSON object: here. I've also tried using the same request but replacing the destination with a local JSON file hosted in the same directory, which also fails with a 404 error. I'm guessing this means that the error is either with my getJSON request, or with my node.js server configuration.

This is the function that makes the getJSON call:

function loginFunction(){
        //check browser support
        if(typeof(Storage) !== "undefined"){
            //store dat shit
            sessionStorage.setItem("username", document.getElementById('username').value);
            sessionStorage.setItem("password", document.getElementById('password').value);
            $(document).ready(function(){
                $.getJSON(createUsernameURL(), function(data){
                    console.log(data);
                    var responseUsername = data.username;
                    document.getElementById("unresult").innerHTML = responseUsername;
                    var responsePassword = data.password;
                    document.getElementById("pwresult").innerHTML = responsePassword;
                });
            });
        }else{
            document.getElementById("pwresult").innerHTML = "your browser is out of date";
        }

And this is the config file for my node.js server:

const http = require('http');
const express = require('express');
const app = express();

app.listen(3000,function(){
    console.log(__dirname)
});

app.get('/', (req,res) => {
    res.sendFile(__dirname + '/index.html');
});

app.use("/static", express.static(__dirname + '/static'));

The createUsernameURL() function just appends a couple pieces of user-entered information to a base URL, but even hard-coding the exact database link mentioned above gives the same issues.



via Clayton Keleher

Pass session to Angular from Node

Im creating a single page app. I have a sign in form in angular:

<div ng-controller="loginCtrl">
    <form>
        <input type="text" ng-model="user.username">
        <input type="password" ng-model="user.password">
        <button ng-click="senduser(user)">Login</button>
    </form>
</div>

Controller:

MyApp.controller("loginCtrl", function($scope, $http){
    $scope.senduser = function(user){
       $http.post("/login", user).then(function(response){
            if(response){
                console.log(response);
            } else {
                console.log("No Data");
            }
        });
      }
});

I can get the user authenticated by using PassportJS:

passport.use(new LocalStrategy(function (username, password, done) {
    User.findOne({username: username}, function (err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false);}
        if (user.password != password) { return done(null, false); }

        return done(null, user);
    });
  }
));

And the node route:

app.post("/login", passport.authenticate('local', {
    failureRedirect : '/login',
    successRedirect: '/loginsuccess'
}));

app.get('/login', function(req, res){
    res.send("Try again")
});

app.get('/loginsuccess', function(req, res){
    res.send("You are Authenticated : ");
});

So far everything works. I want to redirect the successRedirect and failureRedirect to same path \ but only have the session for the user who is authenticated. So based on the authentication, certain fields will be visible on the \ page.

How do I do that ?



via Somename

Using Heroku environment variables with angular-cli, deployed through Node server

I really like Django's implementation of using dotenv variables on Heroku and would like to bring it to our angular-cli client (Angular 2).

In order to run the client on Heroku I'm running the app through Node running express server.

  1. Node can access Heroku's env variables using process.env.VARNAME, but I didn't understand how to pass those variables to my app.
    How can I read Heroku's variables in my app?

  2. As far as I understand, when using angular-cli I should use environment.ts/environment.prod.ts files to separate environment settings.

    However, I don't want to upload these vars to Bitbucket - which brought me back to questioning how to set those variables from Heroku's vars (of course process.env.VARNAME doesn't work...)

Is that the recommended practice or am I missing something?



via Noam Gal

Elasticsearch query with aggregation across two types (I think)

I am trying to figure a way to do this query in Elasticsearch and am having a very hard language. I don't think I know exactly what to search for or research to find the answer and this seems way out of my league in terms of a basic Elasticsearch query.

Anyways, I have two types (really I have about 8 but this pertains only to two of them) in my Elasticsearch instance. Lets call them Invitees and Answers. Now the invitees model has an array of invitees which is basically "who has been invited to answer questions about this particular request". A special thing to note is that the invitees are invited by their role and expertise, and not by a user name, however when a user answers, their user name is tracked as there can be multiple people with the same role/expertise that answer questions about a request.

The Invitees model looks like this requestId: String, invitees:[ { role: String, expertise: String
} ]

The Answers model looks like this. I will spare the unimportant fields here, but the answers model is created each time a person answers a question for a request. Anyone can answer questions about a request, however in the particular query I will get to will only be able the invited roles/expertise.

requestId: String (should match the invitees requestId), role: String, expertise: String, username: String, answers: Array of questions which were answered.

The query I am trying to write deals with querying both the answers and invitees type and finding all instances where the invited roles/expertises ALL answered questions for a given request. Basically a query which would essentially be able to find the roles/expertises invited, ensure that there is at least one Answer type for each of them for the request and return that request ID (which is attached to both the invitee and answer models). Since anyone can answer questions about any request, its not as simple as counting the number of answer types and matching that to the length of the array within the invitee type. In terms of the questions specifically, they do not matter. If a user answers a question an answer type will be created for them in the Elasticsearch instance. If there are no answers in the instance then that means that no one has answered any questions. The Request type is also available in the Elasticsearch instance, however the request ID is attached to both the invitees and answers model so I don't think it needs to be involved in the query.... but I am not 100% sure at this point.

I will take any solution that doesn't result in grabbing all documents out of Elasticsearch and doing some intense iteration on the results in some other language. I am really at a loss here.

I am sure that this is not the best way to have this system set up, however I was kind of dropped into this with the requirement of delivering a solution. I have had to do several other types of queries for this specific system and have eventually found a way to do them.... but this one... this one I just cannot seem to gain any ground on. Also, if it matters I am working in a MEAN stack environment.



via Chris D.

Will Dataflow ever support Node.js with and SDK similar to Java or Python?

I like the philosophy behind DataFlow and found the Java and Python samples highly comprehensible. However, I have to admit that for most Node.js developers who have little background on typed languages and are used to get up to speed with frameworks incredibly fast, learning Dataflow might take some learning curve that they/we're not used to. So, I wonder if at any point in time Dataflow will provide a Node.js SDK. Maybe this is out of the question, but I wanted to run it by the team as it would be awesome to have something along these lines!

Thanks!



via Diego

What's the most efficient way to check if element exists in a set while also querying the document containing the set in NodeJs and MongoDB?

so in my MongoDB database I have a collection holding user posts.

Within that collection I have a set called "likes", which holds an array of the ids of the users that have liked that post. When querying I would like to pass a user id to my query and have a boolean in the result telling me whether the id exists in the array to see whether the user has already liked the post. I understand this would be easy to do with two queries, one to get the post and one to check if the user has liked it, but I would like to find the most efficient way to do this.



via Duxducis

Query Multiple Partition Keys At Same Time DynamoDB - Node

I have an array of Job ID's.

[ '01', '02', '03', '04' ]

Currently I am looping through the array and executing a Query for each item in the array to get the job details.

Is there a way to use a single query to get all the jobs whose Partition Key is in the array ?



via realseanp

Twitter api search tweets tweeted by user

I'm trying to search tweets tweeted by a specific user, but I can't decipher the documentation.

I read through this page https://dev.twitter.com/rest/public/search, and this page https://dev.twitter.com/rest/reference/get/search/tweets and I can see that there is no parameter user or something similar.

But at the bottom of the first page is:

When you want the most popular tweets of a specific user using a hashtag:

You want: popular Tweets from @Cmdr_Hadfield mentioning the hashtag #nasa
Your search URL is: https://api.twitter.com/1.1/search/tweets.json?q=from%3ACmdr_Hadfield%20%23nasa&result_type=popular

Why isnt that documented on the page anywere? Is %3A = @? How do I actually make that search?



via Bogdan Daniel

Node throw new Error('Can\'t set headers after they are sent.')

I am having the above problem with one of my node calls. To my knowledge this error shows if you res.send gets called more than once. Looking at the code it should only send res once so I am not sure what is wrong here.

It throws the error when I insert

        else {
            res.send("Username or Password is wrong");

        }




var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var cors = require('cors');
var massive = require('massive');
var config = require('./config');
var app = express();

app.use(bodyParser.json());
app.use(cors());

var db = massive.connect({connectionString: config.connectionString}, function(err, localdb){
    db = localdb;
    app.set('db', db);

});

app.post('/api/login', function(req, res, next) {

    db.get_users(function(err, users) {
        if(err) res.status(500).json(err);
        else {
            for(var i = 0; i < users.length; i++) {
                if(req.body.email == users[i].email && req.body.password == users[i].password) {
                    console.log("matched");

                    var currentUser = users[i];
                    res.send({
                        msg: 'passed',
                        user: currentUser
                    })
                }
                else {
                    res.send("Username or Password is wrong");

                }
            }
        }

    })
})

app.listen(3000, function() {
    console.log("I am listening");
})



via Yh1234

Segmentation fault on Vuejs client - Debian Server

Im working on a Vue App. I develop it on Windows and it works fine - no errors. But when I copy my project (except of the node modules) to my Debian server, install all dependencies and start it I get this error: Segmentation fault. I found the error is based in the src folder. If I copy any file from there (except the assets folder / files) the Segmentation fault error appears but not if I copy my modified config and build files.



via abbrechen

Module build failed: Error: Couldn't find preset "es2015" relative to directory "/app"

I see so many people ask very similar question but no answer helps me.

So: when I run "npm install" command I am getting the very error.

What I find most unnerving is that my package.json looks like this:

{ 
      "scripts": {
        "lint": "eslint src",
        "postinstall": "webpack",
        "start": "node app.js"
      },
      "engines": {
        "node": ">=6.0.0"
      },
      "devDependencies": {
        "babel-core": "^6.24.0",
        "babel-loader": "^6.4.1",
        "babel-preset-es2015": "^6.24.0",
        "babel-preset-react": "^6.23.0",
        "babel-preset-stage-0": "^6.22.0",
        "css-loader": "0.23.1",
        "eslint": "2.7.0",
        "eslint-plugin-react": "5.2.2",
        "node-sass": "3.8.0",
        "sass-loader": "4.0.0",
        "sockjs-client": "^1.1.1",
        "style-loader": "0.13.1"
      },
      "dependencies": {
        "axios": "^0.15.3",
        "babel-cli": "^6.23.0",
        "body-parser": "^1.17.1",
        "express": "^4.15.2",
        "file-loader": "^0.10.1",
        "mongodb": "^2.2.24",
        "react": "^15.4.1",
        "react-addons-css-transition-group": "^15.4.2",
        "react-addons-transition-group": "^15.4.2",
        "react-dom": "^15.2.1",
        "react-select": "^1.0.0-rc.3",
        "reactstrap": "^4.2.0",
        "webpack": "^1.14.0"
      }
    }

So the dependency for es2015 is already there. What can I be doing wrong?

~ $ cat .babelrc
{
  "presets": ["es2015", "stage-0", "react"]
}

~ $ npm ls babel-preset-es2015
xxx-landing-pae@1.0.0 /app
`-- (empty)



via Novellizator

Firebase querying - issue with indexing unique ids

My database structure looks like this (simplified):

{
  "articles": {
    "article1": {
      "title": "Article 1",
      "category": "news"
    },
    "article2": {
      "title": "Article 2",
      "category": "other"
    },
    "article3": {
      "title": "Article 3",
      "category": "news"
    },
    "article4": {
      "title": "Article 4",
      "category": "news"
    }
  },
  "articlesByCategory": {
    "news": {
      "article1": true,
      "article3": true,
      "article4": true
    },
    "other": {
      "article2": true
    }
  }
}

The query needs to fetch articles where a specific article's category isn't within. Does that make sense? Say, if article4 is of category "other", the query would only fetch articles within "news" and all other existing categories. But since the list may contain, say millions of articles, I have to be as specific as possible and not fetch articles that doesn't match this exact criteria. Therefor, a query like below would be ideal:

const ref = firebase.database().ref("articlesByCategory");
ref.orderByChild("article2").equalTo(null).once("value", function(snapshot) {
  console.log(snapshot.key);
});

Here I am searching for categories where a specific property is absent (where a property equals to null). This is explained here: Firebase: Query to exclude data based on a condition

However, doing a query like this requires me to index every article's unique id on "/articlesByCategory" in the security rules. But it would be unrealistic and non-optimal to dynamically add new article ids inside the ".indexOn" array as that would end up with millions of unique (auto-generated) ids:

{
  "articles": {
    ".read": true,
    ".write": true
  },
  "articlesByCategory": {
    ".read": true,
    ".write": true,
    ".indexOn": ["article1", "article2", "article3", "article4"...] // List would be endless!
  }
}

So how is this achievable? Why am I seeing these sorts of structures (inverted indexing) as ideal solutions everywhere on StackOverflow, but no one seems to tackle this issue?



via Nordling Art

Return json object in controller with placeholder keyword

I am working through a node js, express js, and angular js project and the example given for a controller is not how I have it written. I cannot seem to find any articles explaining the form.

module.exports = {
  index: function(req,res){
    //your code here
    res.json({placeholder:'index'});
  }
}

I understand the res.json is returning the json object, but I'm not familiar with placeholder:'index'.



via JSim

Alexa Called Lambda Function that Queries MySQL database loops forever

When I try running the following lambda function I get the appropriate value added to my MySQL database, however, the Alexa skill outputs an error and trying to delete the value from my database shows that it immediately gets added again forever until I change the name of the table (then I guess it errors and eventually stops).

I have the MySQL bit firing when I call any Alexa Intent from my skill. I don't know callbacks and Alexa contexts that well, so I imagine I'm doing something incorrect handling those. It seems like the query command is getting called many times, which I don't understand since at the end of every callback "route" I have either context.succeeds or context.fails, which should end my Lambda function and give Alexa what it needs to continue with the output needed by the skill.

Here's my current code:

var mysql = require('mysql');
var connection = mysql.createConnection({
    host: '-',
    user: '-',
    password: '-',
    database: '-'
});

exports.handler = (event, context) => {
    try {

        if (event.session.new) {
            // New Session
            console.log("NEW SESSION");
        }


        switch (event.request.type) {

            case "LaunchRequest":
                // Launch Request
                console.log(`LAUNCH REQUEST`);
                context.succeed(
                    generateResponse({},
                        buildSpeechletResponse("Welcome to an Alexa Skill, this is running on a deployed lamda function", true)
                    )
                );
                break;

            case "IntentRequest":
                // Intent Request
                console.log(`Intent Request`);
                console.log('Then run MySQL code:');
                connection.connect(function(err) {
                    console.log('Inside connection.connect() callback');
                    if (!err) {
                        console.log("Database is connected ... ");
                        connection.query("INSERT INTO Users (user_id) VALUES ('TESTNAME')",
                            function(err2, result) {
                                console.log("Inside connection.query() callback");
                                if (!err2) {
                                    console.log("Query Successful! Ending Connection.");
                                    connection.end(function(err3) {
                                        if (!err3) {
                                            console.log("Connection ended!")
                                            context.succeed(
                                                generateResponse({},
                                                    buildSpeechletResponse("Welcome to the incredible intelligent MySQLable Alexa!", true)
                                                )
                                            );
                                        } else {
                                            console.log("Ending connection failure!");
                                            context.fail("Ending connection failure! " + err3.message);
                                        }
                                    });
                                } else {
                                    connection.end(function(err3) {
                                        if (!err3) {
                                            console.log("Query error! Ending Connection!");
                                            context.fail(`Query error! Ending Connection!` + err2.message);
                                        } else {
                                            console.log("Query error and Error ending connection!" + err2.message + " " + err3.message);
                                            context.fail("Query error and Error ending connection!" + err2.message + " " + err3.message);
                                        }
                                    });
                                }
                            });
                    } else {
                        console.log("Error connecting database3 ..." + err.message);
                        context.fail("Error connecting database3 ... " + err.message);
                    }
                });

                break;

            case "SessionEndedRequest":
                // Session Ended Request
                console.log(`SESSION ENDED REQUEST`);
                break;

            default:
                context.fail(`INVALID REQUEST TYPE: ${event.request.type}`);

        }

    } catch (error) {
        context.fail(`Exception: ${error}`);
    }

};

//Helpers
buildSpeechletResponse = (outputText, shouldEndSession) => {

    return {
        outputSpeech: {
            type: "PlainText",
            text: outputText
        },
        shouldEndSession: shouldEndSession
    };
};

generateResponse = (sessionAttributes, speechletResponse) => {
    return {
        version: "1.0",
        sessionAttributes: sessionAttributes,
        response: speechletResponse
    };
};



via Paul McElroy

Sorting in monk not sorting correctly

I've written an app that leverages mongodb for storing some documents, and I'm trying to sort by the date field. When I run the query directly in the mongo shell it works perfectly fine, however it completely goes to shit in monk.

VisitsCollection.find({
            "visitor.attachments.approved.dateSigned": {
                $gte: new Date(d) // d is 6 months back
            }
        }, {sort: { "date": -1 }, limit: 30, skip: page * offset })

^ That's the sorting code I'm using.

Returned dates from monk (formatted in frontend, sorry bout that):

Mar 2, 2017
Mar 16, 2017
Mar 12, 2017
Mar 12, 2017
Mar 12, 2017
Mar 9, 2017
Mar 9, 2017
Mar 8, 2017
Mar 8, 2017
Mar 6, 2017
Mar 6, 2017
Mar 6, 2017
Mar 4, 2017
Mar 3, 2017
Mar 3, 2017
Mar 14, 2017

And this is the result in mongo:

> db.visits.find({}, {"date": 1}).sort({date: -1});
{ "_id" : ObjectId("58ceec2dbc29845efd24e135"), "date" : ISODate("2017-03-25T18:35:17.171Z") }
{ "_id" : ObjectId("58ca7742fab5a11864228231"), "date" : ISODate("2017-03-15T23:32:42.020Z") }
{ "_id" : ObjectId("58ca7742fab5a11864228503"), "date" : ISODate("2017-03-15T17:58:23.336Z") }
{ "_id" : ObjectId("58ca7742fab5a118642283c2"), "date" : ISODate("2017-03-15T12:33:53.917Z") }
{ "_id" : ObjectId("58ca7742fab5a118642281c7"), "date" : ISODate("2017-03-15T09:07:51.754Z") }
{ "_id" : ObjectId("58ca7742fab5a11864228280"), "date" : ISODate("2017-03-15T08:25:19.475Z") }
{ "_id" : ObjectId("58ca7742fab5a1186422827f"), "date" : ISODate("2017-03-15T07:52:34.506Z") }
{ "_id" : ObjectId("58ca7742fab5a11864228587"), "date" : ISODate("2017-03-15T00:56:43.998Z") }
{ "_id" : ObjectId("58ca7742fab5a1186422847d"), "date" : ISODate("2017-03-14T14:10:34.946Z") }
{ "_id" : ObjectId("58ca7742fab5a11864228499"), "date" : ISODate("2017-03-14T02:08:02.714Z") }
{ "_id" : ObjectId("58ca7742fab5a11864228351"), "date" : ISODate("2017-03-14T01:44:17.546Z") }
{ "_id" : ObjectId("58ca7742fab5a118642283e9"), "date" : ISODate("2017-03-14T00:44:02.844Z") }
{ "_id" : ObjectId("58ca7742fab5a118642284c5"), "date" : ISODate("2017-03-12T23:26:23.182Z") }
{ "_id" : ObjectId("58ca7742fab5a1186422835f"), "date" : ISODate("2017-03-12T19:21:59.451Z") }
{ "_id" : ObjectId("58ca7742fab5a118642284a9"), "date" : ISODate("2017-03-12T08:04:17.950Z") }
{ "_id" : ObjectId("58ca7742fab5a118642282bd"), "date" : ISODate("2017-03-12T05:28:20.945Z") }
{ "_id" : ObjectId("58ca7742fab5a1186422842c"), "date" : ISODate("2017-03-12T02:26:53.589Z") }
{ "_id" : ObjectId("58ca7742fab5a1186422838e"), "date" : ISODate("2017-03-12T00:02:53.632Z") }
{ "_id" : ObjectId("58ca7742fab5a118642282ba"), "date" : ISODate("2017-03-11T11:27:44.405Z") }
{ "_id" : ObjectId("58ca7742fab5a118642283f3"), "date" : ISODate("2017-03-11T09:22:47.131Z") }



via yusijs

Elastic Beanstalk: How to write files to a folder in my node.js project folder

I created an application on my local machine(mac os x) that generates a report and saves it to a folder in my web project folder. When I deploy the app., this folder should get published as well. Granted, no one should have access to this folder but the app. When I run the code to generate the report works fine on my local machine, but it seems to hang on elastic beanstalk. What do I need to do to make this work on the elastic beanstalk environment?



via user1790300

Node Js Worker Process Dying Abruptly on Windows

I am running a node js cluster on windows and I can see that the worker process are dying abruptly with a non standard error code.

worker 2136 died (3221225477). restarting...
worker 2172 died (3221226505). restarting...

These numbers are windows error codes.

3221225477 – 0xC0000005 Access Violation error
3221226505 – 0xc0000409 Exception Unknown  

Are these errors logged in Windows Event Viewer or any other log where I can co-relate with node.js process deaths?

Any suggestions on how to debug this will be helpful.



via Ranjan

Google datastore returning weird response

Environment details

OS: Ubuntu 16.04
Node.js version: 7.7.3
npm version: 4.1.2
google-cloud-node version: 0.49

I insert the following entity, but it will fail because the entity already exists:

var transaction = datastore.transaction();
                    transaction.run(function(err) {
                        if (err) {
                            // Error handling omitted.
                            return callback('Database Error');
                        }

                    transaction.save([{
                        key: datastore.key(mykind, mykey]),
                        method: 'insert',
                        data: [{
                            name: 'par1',
                            value: val1
                        }, {
                            name: 'par2',
                            value: val2,
                            excludeFromIndexes: true
                        }
                    }]);

                    transaction.commit(function(err) {
                        if (!err) {
                            // Transaction committed successfully.
                            return callback(null, 'Everything is cool!');
                        }
                         console.log(err);
                    });
                });

The error output is very hard to parse. Err returns this:

"{\"error\":\"Error: entity already exists: app: \\\"s~someapp\\\"<br/>path <<br/> Element {<br/> type: \\\"mykind\\\"<br/> name: \\\"mykey\\\"<br/> }<br/>><br/>\"}"

It returns javascript object but it is difficult to parse if you need the error, type, and name fields. It is not in proper format and there are html entities in the response. Am I doing something incorrect and if so how do I fix this? I want to be able to parse this request.



via user2924127

Create MongoDB Arrays

I'm new to Mongodb.

I have a form textarea with three types of properties.

 "Jobs[]" value ="1"
 "Jobs[]" value ="2"
 "Jobs[]" value ="3"

But my Schema looks like this:

 name: String,
 location: String,
 Jobs: String

How can I insert those multiple jobs from my html to my Schema without creating Jobs1, Jobs2 and Jobs3?

Thank you

If it helps, I'm using express, nodejs and mongoose.



via jomeco1

mongoose, nodejs how to add items into mongo array

I have a collection like { id:"david123", friends[{id:joe321, lname"woo", fname"joe"}] }

i want to add new elements into friends

i currently have this, but it does not seem to be working

app.post('/users/:uid/friends', function(req, res){
  var userId = req.params.uid;
  Friend.update({'_id': userId},
    {$push: {Friends: req.body.friend}},
    { upsert : true },
    function(err, result){
      if (err){
    console.log(err);
  } else {
    res.status(200).json(result);
  }
  })
});

i defined my schema like this

var FriendSchema = new mongoose.Schema({
  _id: String,
  Friends: [{
    _id: String,
    fname: String,
    lname: String
  }]
});



via SanuoXeu

ES6 dynamic imports and instanciation of classes

I'm trying to figure out how to perform dynamic import of classes in ES6 one the server side (node.js with Babel). I would like to have some functionalities similar to what reflection offers in Java. The idea is to import all the classes in a specific folder and instanciate them dynamically.

So for example I could have multiple classes declared in a folder like the one below :

export default class MyClass {

   constructor(somevar) {
       this._somevar = somevar
   }

   //...
   //some more instance level functions here
}

and then somewhere else in my app's code I could have a function that finds out all the classes in a specific folder and tries to instanciate them :

//somewhere else in my app
instanciationFunction(){

   //find all the classes in a specific folder
   var classFiles = glob.sync(p + '/path_to_classes/**/*.js', {
       nodir: true
   });

   _.each(classFiles, async function (file) {
       console.log(file);

       var TheClass = import(file);
       var instance = new TheClass();

       //and then do whatever I want with that new instance

   });
}

I've tried doing it with require but I get errors. Apparently the constructor cant be found.

Any idea would be greatly appreciated.

Thanks



via azpublic

Nodejs Express - Why won't my static file be served?

Ive been looking a all kind of posts and just can't understand my mistake. Whatever I do, my css file is just not being served.Does anyone know why?

test/server/app.js:

            var express = require('express');
            var path = require('path');
            var app = express();

            app.use(express.static(path.join(__dirname, 'public')));
            app.use(express.static(path.join(__dirname, 'browser')));
            var PORT = process.env.PORT || 1337;
            app.listen(PORT, function() {
                console.log('Server is listening!');
            });

test/browser/index.html:

            <head>
                <base href="/" />
                <title>Test</title>
                <link rel="stylesheet" type="text/css" href="public/style.css" />
                <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>

                <script src="app.js"></script>
                <script src="js/app.controller.js"></script>
            </head>

            <body>
                <p>hello world</p>

            </body>
            </html>

My css file is in test/public/style.css



via javascript2016

handling multiple ports for video streaming (via jsmpeg) on ec2

i'm new to video streaming and am confused as to how to use multiple ports for web pages on ec2 to accomplish video streaming.

The streaming tutorial i'm using is http://github.com/phoboslab/jsmpeg

It works perfectly on my local machine: i load the web page with a video player on 8080 and use ffmpeg to stream my laptop camera feed on 8081

then, i got curious and wanted to deploy it on ec2.

i used http://www.lauradhamilton.com/how-to-set-up-a-nodejs-web-server-on-amazon-ec2 to do port forwarding to re-route 80 to 8080 and can load the web page just fine.

however, when i push my camera feed now i get broken pipes. presumably because i explicitly set up port 8080 and not 8081.

but i'm pretty lost on how to handle port 8081. would really appreciate help on this!



via stanley

Populating an array with data from an SQL database and using that array within functions (Javascript, Angular, Node, SQL)

I'm trying to create a Cards Against Humanity clone in an attempt to solidify my understanding of the MEAN stack. I'm very new to Angular and asynchronous programming so please bear with me.

So far I've created a shuffled deck of cards via a GET request, but now I'd actually like to use that data.

I'm populating an array like so:

self.blackCardDeck = [ ];

getCards();

function getCards(){
    $http({
    method: 'GET',
    url: '/cards'
    }).then(function(response){
    self.blackCardDeck = response.data;
    });
}

This code is getting all of the card data from my database, and then populates the array (my shuffled deck). Rather than simply using this in my html, I'd like to be able to use this array in other functions.

For example: I'd like to create a function that uses this deck, slices 6 cards, and sets this new array to the cards that a player is holding.

Something like:

function player(playerName) {
  this.playerName = playerName;
  this.currentCards = [];
}

player1 = new player("Player 1");

var playerArray = [player1, player2, player3, player4];

for (var i = 0; i < playerArray.length; i++) {
 self.playerArray[i].currentCards = self.blackCardDeck.slice(0, 7);  
}

Obviously with the way my code is currently, that's not possible.

Could someone give me some suggestions on where to go from here?

I know I could populate a JSON file with the card information, but I really need to practice async and working with databases. Additionally, I'd eventually like to give users the option to create custom decks, which would potentially require a database(?).

Any recommended reading/general recommendations on my code is greatly appreciated!



via Arrielle Kooiman

Node core modules location

After installation of nodejs where can I find the core modules themselves? What is the path to them on my Linux machine? For example I want to see where is the fs module.



via Nataly

Can't set headers after they are sent Node / Express

I am trying to post data from a form on the client side using jquery to a post route that sends data to an api in node / express.

I am getting the error Can't set headers after they are sent and I can't figure out why.

How can I fix this?

Client:

<input id="prospect-form" type="text" placeholder="Email Address" class="form-control" style="vertical-align: baseline; display:inline-block; background-color: white; border: none;" onClick="submitData()" />

<script charset="utf-8">
    var submitData = function() {
      var data = $("prospect-form").serialize();
      $.post("/prospect/" + data, function() {
        console.log("data sent");
      })
      .done(function() {
        console.log("data success");
      })
      .fail(function() {
        console.log("data failed");
      })
      .always(function() {
        console.log("data finished");
      })
    }
</script>

Express:

router.post('/prospect/:query', function(req, res) {
  var data = req.params.query;
  var options = {
    url: "https://prospect.io/api/public/v1/prospects",
    formData: data,
    headers: {
      "Authorization": "",
      "Content-Type": "application/vnd.api+json; charset=utf-8",
    }
  }

  function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info);
    }
  }

  request.post(options, callback) //post

  res.end()

}) //router post

Thanks so much!



via Quesofat

How to unit test mongoose model?

So I tried to find this out on my own for the whole day. I've found some tips, but that's not enough.

I want make a query and manipulate with it's result. Problem is, the library I've used doesn't allow for that, as it returns a string, or object format. It doesn't simulate the result. Or at least I couldn't achieve it that way.

my code:

• controller:

  const UserMock = sinon.mock(User)
  const expectedResult = {
      "_id" : "58cc67ab9b11ec4cfd9ebb6e",
      "email" : "test@email.com", 
      "password" : "$2a$10$3Oka.IuS/xoGJ4CgxWOPVerE.IVvKemsZchegvwsxopSwIJ08G1P."
    }

  UserMock
    .expects('findOne').withArgs({ email: 'test@email.com' })
    .chain('exec')
    .resolves(expectedResult)

  User.findByEmail('test@email.com')
    .then((user) => user.comparePassword('password'))
    .then((user) => user.publishParse(user))
    .then((user) =>
    {
      UserMock.verify()
      UserMock.restore()
      assert.equal(user, expectedResult)
      done()
    })
    .then(console.log)
    .catch(console.log)

• model:

...

const userSchema = new Schema({
  email: {
    type: String,
    required: true,
    unique: true,
    dropDups: true,
    minlength: [5],
    validate: {
      isAsync: true,
      validator: isEmail,
      message: 'Invalid email'
    }
  },
  password: {
    type: String,
    required: true,
    minlength: [6, "Password must has at least 6 chars."]
  }
}, {
  toJSON: {
    transform: function(doc, ret)
    {
      ret.id = ret._id
      delete ret._id
      delete ret.__v
    }
  }
})

userSchema.methods.comparePassword = function(password)
{
  return new Promise((resolve, reject) =>
  {
    bcrypt.compare(password, this.password, (err, isMatch) =>
    {
      if (err || !isMatch)
      {
        return reject(err)
      }

      resolve(this)
    })
  })
}

userSchema.methods.publishParse = function()
{
  let _user = this.toJSON()
  delete _user.password
  return _user
}

userSchema.statics.findByEmail = function(email)
{
  return this.findOne({ email }).exec()
}

const User = mongoose.model('User', userSchema)
export default User

Libraries I used:

  • mongoose
  • mocha
  • sinon
  • sinon-mongoose


via Patryk Cieszkowski

deepstream list subscribing to data

is it possible in deepstream to subscribe to data using a list? it appears that changes to the data does not trip the subscribe() function, only something like an addEntry() appears to affect the list subscription.

const   deepstream      = require('deepstream.io-client-js')            ;
const   util            = require('util')                               ;

const   client  = deepstream('localhost:6020').login();

var obj_1       =       { 'sequelizeName':'Mark', 'sequelizeAddr':'123 Elm Lane'    , 'sequelizeId':'1111'};
var obj_2       =       { 'sequelizeName':'Lori', 'sequelizeAddr':'948 Maple Street'    , 'sequelizeId':'2222'};

const rec_1     = client.record.getRecord('obj_one');
const rec_2     = client.record.getRecord('obj_two');

rec_1.set(obj_1);
rec_2.set(obj_2);

var listTest    =       client.record.getList('listTest');

listTest.setEntries(    ['obj_one' ,'obj_two' ] );

listTest.subscribe( (result) => {
        console.log('LIST SUBSCRIBE: ' + util.inspect(result));
})

setTimeout( () =>       {
        obj_1.sequelizeAddr = '321 New Address';
        rec_1.set(obj_1); // how can this change show up in the list subscribe?
}, 2000 );

I have been encouraged to try a new approach using lists, but I am unclear how to subscribe to changes in the data itself using a list, except to somehow have some sort of "generic" or "global" subscribe, which i am not sure is even possible.

Or is there some way I can subscribe using an anonymous record?



via edwardsmarkf

Cross site session with NodeJS/Passport/Express backend w/Polymer in front

I've got a node/express/passport backend listening on port 3001 which I'm hitting directly with the browser to authenticate. It authenticates and controls access to protected urls just fine. The front-end is polymer and served on a different port(8080) for dev. After authentication express redirects the browser to the polymer app. The problem is when the polymer app then makes an iron-ajax call back to the express backend, the auth cookie/session handle doesn't get passed, so the backend denies the request.

In production I'm thinking the backend will be on a different sub-domain (backend.foo.com) from the frontend (users.foo.com). Curious if anyone knows how to get express/passport to set a session cookie that will be shared across all the sub domains?



via Richard Rowell

Html5 Nodejs Socketio Multiplayer Game with bouncing balls

I am a beginner at multiplayer game development. I am trying to code a multiplayer game running on node.js socket.io html5. I have already the players which are created on server's side. Now I have a problem with creating the balls on server's side. Here's my scenario:

  1. Server creates an amount of balls
  2. Then it emits to all connected users
  3. Each user receives the balls
  4. Then the server tries to move the balls
  5. On each movement the server emits the new coordinates x,y of each ball to clients
  6. Client receives the balls and tries to draw them in the main loop

I can get the balls on each client's side but the balls are not changing their coordinates which means they are not updating the new values that the server had emitted before. Below is my code. If anyone could see it and tells me where I make mistake I would be so thankful.

the html code: simpleChat.html

<style>
#myCanvas {
  border: 1px solid red;
  background-color:pink;
}
</style>
<script src="jeu.js"></script>
<script src="/socket.io/socket.io.js"></script>

<script>
        var username = prompt("What's your name?");
        var conversation, data, datasend, users;

        var socket = io.connect();

        // on connection to server, ask for user's name with an anonymous callback
        socket.on('connect', function(){
                // call the server-side function 'adduser' and send one parameter (value of prompt)
                socket.emit('adduser', username);
        });

        // listener, whenever the server emits 'updatechat', this updates the chat body
        socket.on('updatechat', function (username, data) {
                var chatMessage = "<b>" + username + ":</b> " + data + "<br>";
                conversation.innerHTML += chatMessage;
        });

    // just one player moved
        socket.on('updatepos', function (newPos) {
    console.log('client: '+newPos.user +' has to update pos to ['+newPos.x+','+newPos.y+']');
                updatePlayerNewPos(newPos);
        });

        // listener, whenever the server emits 'updateusers', this updates the username list
        socket.on('updateusers', function(listOfUsers) {
                users.innerHTML = "";
                for(var name in listOfUsers) {
                var userLineOfHTML = '<div>' + name + '</div>';
                users.innerHTML += userLineOfHTML;
                }
        });

        // update the whole list of players, useful when a player
        // connects or disconnects, we must update the whole list
        socket.on('updatePlayers', function(listOfplayers) {
                updatePlayers(listOfplayers);
        });

        // on load of page
        window.addEventListener("load", function(){
                // get handles on various GUI components
                conversation = document.querySelector("#conversation");
                data = document.querySelector("#data");
                datasend = document.querySelector("#datasend");
                users = document.querySelector("#users");

                // Listener for send button
                datasend.addEventListener("click", function(evt) {
                sendMessage();
                });

                // detect if enter key pressed in the input field
                data.addEventListener("keypress", function(evt) {
                // if pressed ENTER, then send
                if(evt.keyCode === 13) {
                                this.blur();
                        sendMessage();
                }
                });

                // sends the chat message to the server
                function sendMessage() {
                        var message = data.value;
                        data.value = "";
                        // tell server to execute 'sendchat' and send along one parameter
                        socket.emit('sendchat', message);
                }
        });

</script>

<body onload="init();">
        <p>
<canvas width = 600 height = 400 id="myCanvas"></canvas>
<p>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
        <b>USERS</b>
        <div id="users"></div>
</div>
<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
        <div id="conversation"></div>
        <input id="data" style="width:200px;" />
        <input type="button" id="datasend" value="send" />
</div>

</body>
server's side server.js => in command prompt: node server.js

// We need to use the express framework: have a real web servler that knows how to send mime types etc.
var express = require('express');

// Init globals variables for each module required
var app = express()
        , http = require('http')
        , server = http.createServer(app)
        , io = require('socket.io').listen(server);

// launch the http server on given port
server.listen(8082);

// Indicate where static files are located. Without this, no external js file, no css...

app.use(express.static(__dirname + '/'));


// routing
app.get('/', function (req, res) {
    res.sendFile(__dirname + '/simpleChat.html');
});

// usernames which are currently connected to the chat
var usernames = {};
var listOfPlayers = {};
var canvas_d = {};
var oldTime = 0;
var joueurs = new Array();
var currentP = {};
var width = 600, height = 400;
var ballArray=[],ballArrayColor=[];
//var ballPos={};
function Balle(x, y, vx, vy, diameter, ballcol) {
    this.x = x;
    this.y = y;
    this.vx = vx;
    this.vy = vy;
    this.rayon = diameter / 2;
    this.bcolor=ballcol;
/*
    this.draw = function (ballcol) {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.rayon, 0, 2 * Math.PI);
        ctx.fillStyle = ballcol;
        ctx.fill();
//    console.log(ballcol);
    };*/
/*
    this.move = function () {

        this.x += this.vx;
        this.y += this.vy;
    };*/

}
function createBalls(numberOfBalls) {
    for (var i = 0; i < numberOfBalls; i++) {
        var balcolor = getRandomColor();
        // Create a ball with random position and speed
        var ball = new Balle(width * Math.random(),
                height * Math.random(),
                (10 * Math.random()) - 5,
                (10 * Math.random()) - 5,
                15, balcolor); // radius, change if ou like.

        // Add it to the array
        //ballArray[i] = ball;
        ballArray.push(ball);
        ballArrayColor[i] = balcolor;
        //console.log(i, balcolor);
    }

}
function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
function getMax(arr) {
    var maxX = 0;
    var maxY = 0;
    for (var i in arr) {
        if (i !== null) {
            console.log('i not null kaj getMax');
            if (maxX <= arr[i].x) {
                maxX = arr[i].x + arr[i].width;
                if (maxX >= (canvas_d.width - arr[i].width)) {
                    maxX = arr[i].x;
                    if (maxY <= arr[i].y) {
                        maxY = arr[i].y + arr[i].height;
                    }
                }
            }

        } else {
            maxX = arr[i].x;
            maxY = arr[i].y;
        }


    }
    return {'maxX': maxX + 0.5, 'maxY': maxY + 0.5};
}


function checkCollisionWithAnotherPlayer(arr, usr, currentP) {

    for (var name in arr) {
        console.log('other player: ' + name);
        if (usr !== name) {
            if ((arr[usr].x < (arr[name].x + arr[name].width))
                    && ((arr[usr].x + arr[usr].width) > arr[name].x)
                    && ((arr[usr].y + arr[usr].height) > arr[name].y)
                    && (arr[usr].y < (arr[name].y + arr[name].height))) {
                console.log('collision');
                listOfPlayers[usr].x = currentP.x;
                listOfPlayers[usr].y = currentP.y;
            }

        }
    }
}

io.sockets.on('connection', function (socket) {

    // when the client emits 'sendchat', this listens and executes
    socket.on('sendchat', function (data) {
        // we tell the client to execute 'updatechat' with 2 parameters
        io.sockets.emit('updatechat', socket.username, data);
    });


    socket.on('canvas', function (d) {
        canvas_d.width = d.width;
        canvas_d.height = d.height;
    });
    // when the client emits 'sendupdate', this listens and executes
    socket.on('sendupdate', function (input) {
        console.log('socket on sendupdate from ' + input.user);
        currentP = {'x': listOfPlayers[input.user].x, 'y': listOfPlayers[input.user].y};
        oldTime = input.lastMove;
        var now = Date.now();
        console.log('now ' + now);
        //calculating delta time
        var delta = (now - oldTime) / 1000;
        console.log('delta ' + delta);
        listOfPlayers[input.user].speedX = listOfPlayers[input.user].speedY = 0;
        if (input.inputStates.left) {
            listOfPlayers[input.user].speedX = -listOfPlayers[input.user].v;
        } else if (input.inputStates.up) {
            listOfPlayers[input.user].speedY = -listOfPlayers[input.user].v;
        } else if (input.inputStates.right) {
            listOfPlayers[input.user].speedX = listOfPlayers[input.user].v;
        } else if (input.inputStates.down) {
            listOfPlayers[input.user].speedY = listOfPlayers[input.user].v;
        }
        listOfPlayers[input.user].x += delta * listOfPlayers[input.user].speedX;
        listOfPlayers[input.user].y += delta * listOfPlayers[input.user].speedY;

        //player restriction
        if (listOfPlayers[input.user].x < 0)
            listOfPlayers[input.user].x = 0;
        //up wall
        if (listOfPlayers[input.user].y < 0)
            listOfPlayers[input.user].y = 0;
        //down wall
        if (listOfPlayers[input.user].y + listOfPlayers[input.user].height > canvas_d.height)
            listOfPlayers[input.user].y -= delta * listOfPlayers[input.user].speedY;
        //right wall
        if (listOfPlayers[input.user].x + listOfPlayers[input.user].width > canvas_d.width)
            listOfPlayers[input.user].x -= delta * listOfPlayers[input.user].speedX;

        //collision detection with other players
        checkCollisionWithAnotherPlayer(listOfPlayers, input.user, currentP);
        console.log('socket emits to all players the updated position of player: ' + input.user + ' to position: ' + listOfPlayers[input.user].x + ' , ' + listOfPlayers[input.user].y);
        var newPos = {'user': input.user, 'x': listOfPlayers[input.user].x, 'y': listOfPlayers[input.user].y};
        io.sockets.emit('updatepos', newPos);

    });
    //when client emits 'drawBalls' the server will try to move each ball
    socket.on('drawBalls',function(){
        for(var i=0;i<ballArray;i++){
            ballArray[i].x += ballArray[i].vx+10;
            ballArray[i].y += ballArray[i].vy+10;
        }
        var ballPosit={
            'balls':ballArray,
            'colors':ballArrayColor
        };
        socket.emit('updateBallPos',ballPosit);
    });

    // when the client emits 'adduser', this listens and executes
    socket.on('adduser', function (username) {
        // we store the username in the socket session for this client
        // the 'socket' variable is unique for each client connected,
        // so we can use it as a sort of HTTP session
        socket.username = username;
        // add the client's username to the global list
        // similar to usernames.michel = 'michel', usernames.toto = 'toto'
        usernames[username] = username;

        // echo to the current client that he is connecter
        socket.emit('updatechat', 'SERVER', 'you have connected');
        // echo to all client except current, that a new person has connected
        socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
        // tell all clients to update the list of users on the GUI
        io.sockets.emit('updateusers', usernames);

        // Create a new player and store his position too... for that
        // we have an object that is a "list of players" in that form
        // listOfPlayer = {'michel':{'x':0, 'y':0, 'v':0},
        //                                                      john:{'x':10, 'y':10, 'v':0}}
        // for this example we have x, y and v for speed... ?
        var player = {'x': 10, 'y': 10, 'v': 200, 'height': 100, 'width': 100, 'lastUpdate': null, 'name': username};
        var newPlayer;

        newPlayer = getMax(listOfPlayers);
        player.x = newPlayer.maxX;
        player.y = newPlayer.maxY;
        console.log(newPlayer.maxX + ' - ' + newPlayer.maxY);


        joueurs.push(player.username);

        listOfPlayers[username] = player;
        io.sockets.emit('updatePlayers', listOfPlayers);
        
        //creation of balls
        if(joueurs.length===1){
            createBalls(2);
        }
        console.log('taille of joueurs; '+joueurs.length);
        var ballPos={
            'balls':ballArray,
            'colors':ballArrayColor,
            'user':username
        };
       // socket.emit('createBalls',ballPos);
    });

    // when the user disconnects.. perform this
    socket.on('disconnect', function () {
        var index = joueurs.indexOf(socket.username);
        joueurs.splice(index, 1);
        // remove the username from global usernames list
        delete usernames[socket.username];
        // update list of users in chat, client-side
        io.sockets.emit('updateusers', usernames);

        // Remove the player too
        delete listOfPlayers[socket.username];
        io.sockets.emit('updatePlayers', listOfPlayers);

        // echo globally that this client has left
        socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
    });
});
client's side. jeu.js

var canvas, ctx, w, h;
var ballArray = [], ballArrayColor = [];
// for time based animation

// vars for handling inputs
var inputStates = {};

// Autres joueurs
var allPlayers = {};
var now;
function init() {
    console.log("init");
    canvas = document.querySelector("#myCanvas");
    // often useful
    w = canvas.width;
    h = canvas.height;
    ctx = canvas.getContext('2d');
    var canvasDimension = {'width': w, 'height': h};
    socket.emit('canvas', canvasDimension);
    // Les écouteurs
    //canvas.addEventListener("mousedown", traiteMouseDown);
    //canvas.addEventListener("mousemove", traiteMouseMove);
    //createBalls(2);
    socket.on('createBalls',function(data){
        ballArray=data.balls;
        ballArrayColor=data.colors;
    });
    
    window.addEventListener('keydown', movePlayer, false);


    anime();

}



function movePlayer(evt) {
    inputStates.left = false;
    inputStates.up = false;
    inputStates.right = false;
    inputStates.down = false;
    if (evt.keyCode === 37) {
        inputStates.left = true;
    } else if (evt.keyCode === 38) {
        evt.preventDefault();
        inputStates.up = true;
    } else if (evt.keyCode === 39) {
        inputStates.right = true;
    } else if (evt.keyCode === 40) {
        evt.preventDefault();
        inputStates.down = true;
    }
    now = Date.now();
    var input = {'user': username, 'inputStates': inputStates, 'lastMove': now};
    console.log('player' + username + ' wants to move with inputStates: ' + inputStates.up + ' ; ' + inputStates.down + ' ; ' + inputStates.left + ' ; ' + inputStates.right);
    socket.emit('sendupdate', input);
}

function updatePlayerNewPos(newPos) {
    for (var i in allPlayers) {
        if (i === newPos.user) {
            allPlayers[i].x = newPos.x;
            allPlayers[i].y = newPos.y;
            console.log('I have just moved!->  ' + newPos.x + ' ; ' + newPos.y);
        }

    }

}

// Mise à jour du tableau quand un joueur arrive
// ou se deconnecte
function updatePlayers(listOfPlayers) {
    allPlayers = listOfPlayers;
}

function drawPlayer(joueur) {
    // save the context
    ctx.save();
    // draw a red rectangle
    // head
    ctx.fillStyle = 'yellow';
    ctx.fillRect(joueur.x, joueur.y, 100, 100);
    ctx.fillStyle = "grey";
    ctx.fillRect(joueur.x, joueur.y, 100, 10);
    //eyebrows
    ctx.fillStyle = 'black';

    ctx.fillRect(joueur.x + 5, joueur.y + 15, 20, 5);
    ctx.fillRect(joueur.x + 75, joueur.y + 15, 20, 5);

    // eyes
    ctx.fillStyle = 'lightblue';
    ctx.fillRect(joueur.x + 10, joueur.y + 25, 10, 10);
    ctx.fillRect(joueur.x + 80, joueur.y + 25, 10, 10);
    // interior of eye
    ctx.fillStyle = 'blue';
    ctx.fillRect(joueur.x + 13, joueur.y + 27, 5, 5);
    ctx.fillRect(joueur.x + 83, joueur.y + 27, 5, 5);
    // Nose
    ctx.fillStyle = 'brown';
    ctx.fillRect(joueur.x + 50, joueur.y + 35, 8, 15);
    //Moustaches
    ctx.fillStyle = 'grey';
    ctx.fillRect(joueur.x + 43, joueur.y + 63, 25, 5);
    // Mouth
    ctx.fillStyle = 'red';
    ctx.fillRect(joueur.x + 35, joueur.y + 70, 40, 20);
    //teeth
    ctx.fillStyle = 'white';
    ctx.fillRect(joueur.x + 38, joueur.y + 73, 10, 15);
    ctx.fillRect(joueur.x + 50, joueur.y + 73, 10, 15);
    ctx.fillRect(joueur.x + 62, joueur.y + 73, 10, 15);
    // ctx.strokeText(joueur.name,joueur.x+50,joueur.y+50);
    ctx.restore();
}

function drawAllPlayers() {
    for (var name in allPlayers) {
        drawPlayer(allPlayers[name]);
    }
}

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}

function anime() {
    if (username !== undefined) {
        // 1 On efface l'écran
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 2 On dessine des objets
        drawAllPlayers();
          socket.on('updateBallPos',function(data){
        console.log('=== updating the pos of balls');
        ballArray=[];
        ballArrayColor=[];
        ballArray=data.balls;
        ballArrayColor=data.colors;
        
        
    });
    //drawing the balls
    for (var i = 0; i < ballArray.length; i++) {
        var balle = ballArray[i];
        var bc = ballArrayColor[i];
        console.log(balle.x, balle.y, bc);
        // 1) Move the ball
       // balle.move();

        // 2) collision test with walls
        //collisionTestWithWalls(balle);

        // 3) draw the ball
       // balle.draw(bc);
       ctx.beginPath();
        ctx.arc(balle.x, balle.y, balle.rayon, 0, 2 * Math.PI);
        ctx.fillStyle = bc;
        ctx.fill();
    }
    socket.emit('drawBalls','balls are drawn');
    }/*
    socket.on('updateBallPos',function(data){
        console.log('=== updating the pos of balls');
        ballArray=[];
        ballArrayColor=[];
        ballArray=data.balls;
        ballArrayColor=data.colors;
        
        
    });
    for (var i = 0; i < ballArray.length; i++) {
        var balle = ballArray[i];
        var bc = ballArrayColor[i];
        console.log(balle.x, balle.y, bc);
        // 1) Move the ball
       // balle.move();

        // 2) collision test with walls
        //collisionTestWithWalls(balle);

        // 3) draw the ball
       // balle.draw(bc);
       ctx.beginPath();
        ctx.arc(balle.x, balle.y, balle.rayon, 0, 2 * Math.PI);
        ctx.fillStyle = bc;
        ctx.fill();
    }
    socket.emit('drawBalls','balls are drawn');
*/
    //collisionTestBetweenBalls();
    // 4 On rappelle la fonction d'animation à 60 im/s

    requestAnimationFrame(anime);
}


via P Richmond

Node.js/AngularJS: Shrink image files to specific file size

Using a MEAN environment, I would like to automatically shrink image files (.gif/.png/.jpg) which are uploaded by websites users, to a specific file size (e.g. 2 MB). Is there any node.js module available, enabling me to use something like this:

SomeModule.shrinkImage('MyHugeImage.jpg','2MB')
.then()
[...]

Haven't found anything suitable yet. May happen on client (using AngularJS) or server-side (Node.js module), I don't care. Suggestions?



via Igor P.

Getting a database does not exist error for a database that exists

I am trying to connect node with mysql. I have created the code for the connection and using phpmyadmin created a database called sampleDB. When I try to connect I get an Error: ER_BAD_DB_ERROR: Unknown database 'sampledb'. But I have created the database.

Here is my code

var express = require('express');
var mysql = require('mysql');
var app = express()

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'sampleDB'
});

connection.connect(function(error){
    if(!!error){
        console.log(error);
    } else {
        console.log('Connected')
    }
})

app.get('/', function(req, resp){
    connection.query("Select * from mySampleTable", function(error, rows, fields){
        if(!!error){
            console.log('Error in query')
        }else {
            console.log('Success');
        }
    });
})

app.listen(1337);

Here is an image of of the db I created call sampleDB. enter image description here

So if I created the db called sampleDB, why am I getting an error that the sampledb table does not exist?



via Aaron

Gulp task finishing too early

I am struggling with my gulp script exiting too early.

I narrowed down the problem to this:

var gulp = require("gulp");
var through = require("through2");

function Transform() {
    return through.obj(function(file,enc,next) {
        // not calling next(null,file)
    });
}

gulp.task("test",function() {
    return gulp.src("foo")
        .pipe(Transform())
        .pipe(gulp.dest("tmp"));
});

Running gulp test, i would expect gulp never to exit since the stream should be blocked in the Transform operation that never pass the file down. But it returns.

There is obviously something i missed. What is it ?



via Blue4Whale

Understing loops with node

In node js i have a function that iterates trough an array to fill another element. Some times some proprerties are undefined, how can that be? For example i get "cannot read property formattedPrice of undefined". What is wrong with a for loop on node?

for (var i = 0; i < 10; i++) {
    //console.log(JSON.stringify(item.SmallImage));
        message.attachment.payload.elements[i] = {
            "title":items[i].ItemAttributes.Title,
            "image_url": items[i].LargeImage.URL,
            "subtitle":items[i].ItemAttributes.ListPrice.FormattedPrice,
            "default_action": {
            "type": "web_url",
            "url": "https://www.google.it",
            "messenger_extensions": true,
            "webview_height_ratio": "tall",
            "fallback_url": "https://www.google.it"
            },
            "buttons":[
                {
                  "type":"web_url",
                  "url":"https://www.google.it",
                  "title":"View Website"
              },{
                  "type":"postback",
                  "title":"Start Chatting",
                  "payload":"DEVELOPER_DEFINED_PAYLOAD"
              }             
          ]      
        }
    //sendMessage( senderId, {text: item.ItemAttributes.Title+" PREZZO**:"+item.ItemAttributes.ListPrice.FormattedPrice});
    }



via Pjotr Raskolnikov