samedi 9 mai 2015

self decrypting interpreted code (Node.js etc) - looking for weakness

Recently I've tried an super easy way to protect any interpreted code written in Node.JS or any interpreted language out there. I've really tried hard to find similar solution on stack overflow without success.

The method is so easy that it is difficult for me to believe that it could not be easily broken as well. Before I come with the question, let me show you what it is:

The goals are:

  • make the simplest (and quite difficult) method to protect source code interpreted by node binary.
  • the may to be difficult to hack by the average person. I don't want protect my code against professionals.
  • do not change the Node source code itself. What I need is just the use of already compiled Node binary.

The solution:

Write a simple wrapper with C to read encrypted source code, decrypt it and then put decrypted code to the standard input of the node binary using "popen" function from stdio.h. Since the C code can be compiled (and eventualy obfuscated before) it can be quite difficult to reverse-engineer it. Let me describe it in pseudo code snippet below:

#include <stdio.h>
void main() {
    encr_fp = fopen("the_encrypted_code_file", "r");
    pipe_fp = popen("/usr/local/bin/node", "w");
    while (read bunch of bytes from encr_fp != EOF) {
        decrypt bunch of bytes
        put decrypted bunch of bytes to pipe_fp
    }
    pclose(pipe_fp);
} 

So, finally the question is

Can you point some weakness of the method described above ?

the only two drawbacks I can imagine are:

  • is is very easy to replace "/usr/local/bin/node" with my own script to intercept the stdin
  • since the popen starts /bin/sh it can be easy to replace /bin/sh as well to do the same

Fortunately it is very easy to protect the code by adding simple CRC checking of /usr/local/bin/node and /bin/sh binaries before actual decryption.

Can you find some more?

In Node, how do I require files inside eval?

I have two files test.js and x.js, in the same directory:

  • test.js:

    console.log(eval( "require('x.js')" ));
    
    
  • x.js is empty.

Expected: require returns undefined, so nothing is logged.

Actual: node test.js gives me Error: Cannot find module 'x.js' (stack-trace omitted for brevity).

The situation sounds similar to this other question, with the differences that I've used eval rather than new Function, and require is defined, just working unexpectedly.


Why is this?

How do I correctly require a module in eval'd code?

Deployment of Node.js app to production

I am a front-end developer with experience in Ruby on Rails who is currently trying to build an Isomorphic App with React and Node.js. And I have a question about deploying such apps.

While I was developing Ruby applications, there always have been some scripts that would make the deployment process nice and easy — gathering new release from github, uploading it to new release folder, symlinking it to current, precompiling assets. Аnd I can't find something like this for Node.js straight away.

But I am sure that there must be. I am looking for the script that would setup the new virtual machine with all the packages, deploy it, and also would take care of the different environments and their configs (staging, for example). So, what is the idiomatic way to do it with Node.js?

Thanks!

Pass value in routes dir from users.js to index.js in Express Framework

I have used require('fs') in users.js and the files are being read by the code. Now my next task is to pass this q.datastore[] value to index.js in router folder (where the queue function is declared and I haven't posted in my above code)

var ReadlocalDirectory = function() {
   var p = "/home/admin/Documents/Project-1/public/folder/",
   currentFile;
   fs.readdir(p, function (err, files) {
      if (err) {
          throw err;
              }
       files.map(function (file) {
           return path.join(p, file);
          }).filter(function (file) {
            return fs.statSync(file).isFile();
         }).forEach(function (file) {
            q.enqueue(file);
         });
     filesQueue = q.dataStore;
    return filesQueue;//return the value to index.js
   });
};

want to pass the value of filesQueue to index.js

Showing window after it is fully loaded

When I create basic application and initialize it using electron command, it shows me a blank window and a moment later loads the content.

Which event and which object should be used to show the window after the content is fully loaded?

did-finish-load on a window.webContent object? Or maybe dom-ready? Or maybe something else?

app.js:

var app = require('app'),
    Window = require('browser-window'),
    mainWindow = null;

require('crash-reporter').start();

app.on('ready', function() {
   mainWindow = new Window({ width: 600, height: 400, show: false });

   mainWindow.loadUrl('file://' + __dirname + '/index.html');
   mainWindow.show();

   //
   // mainWindow.webContent.on('did-finish-load', function() {
   //     something like that is a proper way?
   // });
   //
});

How to use results from Q Promise inside and outside of promise.spread

I recently started using the q promise javascript library for my Node.js application. In my code I have a conditional that determines if I should execute 1 or 3 promise methods. I then want to execute the array of promise-returning methods and perform additional processing on the results.

Question: How do I use the results inside and outside .spread(...), so I can pass the result to other methods?

Some background: I am building a REST API, where depending on the values of the POSTed JSON body, I have to insert records into the DB using Sequelize first, get a response (so I know the auto-generated primary key), then insert records in other tables using that primary key.

var promiseMethods;

var someParam1, someParam2, someParam3 = 'Hello World';

if (someCondition == true) {

    promiseMethods = [promiseMethod1(someParam1)];
} else {
    promiseMethods = [
        promiseMethod1(someParam1),
        promiseMethod2(someParam2),
        promiseMethod3(someParam3)];
}

Q.all(promiseMethods)
    .spread(function(promseResult1,
                     promiseResult2,
                     promiseResult3) {

    var model = {
        result: promiseResult1
    };

    //Other code removed for brevity.

    return Database.save(model)
});

Count total items in mongoDB collection/database

I can't seem to find the answer to this. I wan't a simple return statement of the amount (total) items in my collections.

var mongojs = require('mongojs');
var db = mongojs("myadb",['myadb']);
db.myadb.count(function(used,a){
    console.log(used,a);
});

Null is return. I'm using a mongodb JS library for node and yes, there is records in the database (12)

The documentation states that:

cursor.count(callback)

Thanks.

Can't install packages -g via nvm (local profile, not sudo)

I'm using nvm running node version 0.12.2.

I try and install bower globally:

karl@karl-laptop:~/www/busarama/src$ npm install -g bower
npm ERR! tar.unpack untar error /home/karl/.npm/bower/1.4.1/package.tgz
npm ERR! Linux 3.16.0-36-generic
npm ERR! argv "/home/karl/.nvm/versions/node/v0.12.2/bin/node" "/home/karl/.nvm/versions/node/v0.12.2/bin/npm" "install" "-g" "bower"
npm ERR! node v0.12.2
npm ERR! npm  v2.7.4
npm ERR! path /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13

npm ERR! Error: EACCES, mkdir '/usr/local/lib/node_modules'
npm ERR!     at Error (native)
npm ERR!  { [Error: EACCES, mkdir '/usr/local/lib/node_modules']
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/usr/local/lib/node_modules',
npm ERR!   fstream_type: 'Directory',
npm ERR!   fstream_path: '/usr/local/lib/node_modules/bower',
npm ERR!   fstream_class: 'DirWriter',
npm ERR!   fstream_stack: 
npm ERR!    [ '/home/karl/.nvm/versions/node/v0.12.2/lib/node_modules/npm/node_modules/fstream/lib/writer.js:171:23',
npm ERR!      '/home/karl/.nvm/versions/node/v0.12.2/lib/node_modules/npm/node_modules/mkdirp/index.js:46:53',
npm ERR!      'FSReqWrap.oncomplete (fs.js:95:15)' ] }
npm ERR! 
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/karl/www/busarama/src/npm-debug.log

I am very suspicious it is due to me running this earlier today:

npm config set prefix /usr/local

Does anyone know what the default npm config prefix should be (when installing -g to the local profile, not sudo)? I installed nvm as a local user.

This is affecting everything I try to install globally.

Found this little nice link: http://ift.tt/1IZaIxM

Local install (default): puts stuff in ./node_modules of the current package root.
Global install (with -g): puts stuff in /usr/local or wherever node is installed.
Install it locally if you're going to require() it.
Install it globally if you're going to run it on the command line.
If you need both, then install it in both places, or use npm link.

  • ...or wherever node is installed.

This means I'm guessing that it should be installed to /home/karl/.nvm/versions/node/v0.12.2 somewhere.

I need to set the npm config prefix to whatever node is running.

Why node server.listen do not returns to shell

Node files can describe from servers to simple scripts, even something that only prints to console:

//logger.js
console.log('Hello World');

// in the terminal
> node logger.js
Hello World
>

How http package (and others) do not give the command prompt back to the user; how do they keep the process alive?

//server
require('http').createServer(function (req, res) {
  res.end('Hello World');
}).listen(3000);

// in the terminal
> node server.js
// process stays in the foreground, no prompt back

Selecting specific fields from a relationship

I'm building a webapp on node.js (sails) with waterline (using mysql adapter).

I've managed to get relationships working like this:

//Post.js attributes
    post_statistics: {
        collection: 'postStatistics',
        via: 'post'
    }

I can easily find the relationship records with the line:

var query = {user:userId}; // Just filtering by the user
query.is_public = Post.POSTS_ONLY_ACTIVE; // Only showing active posts, boolean
query.select = ['id','title','content']; // id is only needed for me to get the join working
Post.find(query).populate('post_statistics').exec(cb);

Everything works fine but I need to only select specific fields from post_statistics. This does not seem to do anything, though, I'd expect it to work:

Post.find(query).populate('post_statistics',{select:['post','user','id']}).exec(cb);

Adding the field names to the initial select is even worse since the fields already target the post table.

Any sane way to make this work or am I going to have to write the whole query?

Thinkster MEAN Stack Tutorial problems with routing

I have been following this tutorial on thinkster.io:

http://ift.tt/1IXiNVv

Everything works fine until I get to the section where we setup mongoose, then I start to hit problems.

First of all in the section "Creating Schemas with Mongoose" it says:

"Connect to our local MongoDB instance by adding the following code into our app.js file:"

But this is unclear - what do they mean by "our" app.js file - we no longer have an app.js that we created as we renamed it to angularApp.js - the only app.js file is the one generated by express/npm which is in the /views/ folder and is full of express configurations. I personally added the code to this file but am unsure if they meant for us to add it to /public/javascripts/angularApp.js

Secondly, in the "Creating our first route" section, the tutorial instructs us to add the code to routes/index.js but again this file is already populated with express routes and the tutorial is unclear as to whether we append this file with the new route for /posts or to remove the existing express route and add the /posts route instead.

Either way, the result is when I attempt to post the first data to mongodb via curl or postman it results in a 404, indicating the route is not working.

Any help appreciated - there is no comment section on the site for asking questions or troubleshooting, so I am hoping stackoverflow can fill in the gaps :)

Javascript make a post request and receive multiple responses

How can I receive multiple response from the server? The server sends to the client 3 different responses. Unfortunately my code catches only the first(I Think) one.

This is the index.html page with the javascript code:

<script type="text/JavaScript">
    console.log('begin');
    var http = new XMLHttpRequest();



    var data={
        'query'        : "test"
    }


    data=JSON.stringify(data);


    http.open("POST", "http://localhost:8080", true);

    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");


    http.onreadystatechange = function() {
        console.log('onreadystatechange');
        if (http.readyState == 4 && http.status == 200) {
            console.log(http.responseText);
        }
        else {
            console.log('readyState=' + http.readyState + ', status: ' + http.status);
        }
    }

    console.log('sending...')
    http.send(data);
    console.log('end');

</script>

In NODE JS I can catch all the responses in this way... is there something similar?

var options = {
    host: 'localhost',
    port: 8080,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length
    }
};

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

Passport "Hello World" always fails

I have the following:

import {Router} from 'express';
import passport from 'passport';
import {Strategy} from 'passport-local';
import pg from 'pg';
import {pgUri} from '../environment';

let loginRouter = Router();

passport.use(new Strategy((username, password, done) => done(null, true)));
//{
//    pg.connectAsync(pgUri)
//        .then(([client, release]) => {
//            return client.queryAsync('select * from users where "user" = $1::TEXT', [username])
//                .finally(release);
//        })
//        .tap(result => console.log(result.rows))
//        .then(result => done(null, true));
//}));

loginRouter.get('/', (request, response) => response.render('login'));
loginRouter.post('/', passport.authenticate('local', {successRedirect: '/',
                                                      failureRedirect: '/login'}));

It's an express route file that defines the simplest possible authentication scheme. The above always redirects back to /login, indicating a failure.

What I've tried

  • Changing failureRedirect to /loginFailed really redirects there. So the login does fail.
  • Breakpoints and console.logs inside the function body do not get hit.
  • Calling done with done(null, {foo: "bar"}) instead of true changes nothing.

Worth noting

  • I'm using babel for ES6 support, but since this is the only part failing, and the breakpoints I can set (before passport.use) show expected values for all variables, I don't think that's the problem.
  • The .get() route works as expected, displaying the form.

Here's the form I'm using (directly copied from the passport example

<form action="/login" method="post">
    <div>
        <label>Username:</label>
        <input type="text" name="username"/>
    </div>
    <div>
        <label>Password:</label>
        <input type="password" name="password"/>
    </div>
    <div>
        <input type="submit" value="Log In"/>
    </div>
</form>

I have no idea what went wrong here. Would appreciate any help.

how to consume wcf in node.js?

I want to consume wcf in node.js. I tried it:

soap.createClient(url, function (err, client) { if (err) { console.log(err); return false; } client.myFunc(args, function(err1, result) { if(result.success) return true; }); });

But an error occurred in createClient (error block). it says: Unexpected root element of WSDL or include . Then I tried by wcf.js:

var BasicHttpBinding = require('wcf.js').BasicHttpBinding
, Proxy = require('wcf.js').Proxy
, binding = new BasicHttpBinding()
, proxy = new Proxy(binding, " http://localhost/myService.svc");
var message = '<Envelope xmlns=' +
            '"http://ift.tt/sVJIaE">' +
            '<Header />' +
            '<Body>' +
            '<myFunc xmlns="http://localhost/myService.svc/">' +
            '<value>'+ args +'</value>' +
            '</AddNewUser>' +
            '</Body>' +
            '</Envelope>';
proxy.send(message, "http://localhost/myService.svc", function (result, ctx){
    if(result.success)
        return true;
    });

But my program didn't call send function. Finally I tried to configure WCF to WSDL publishing like this: WCF cannot configure WSDL publishing

But it didn't work to! How can I solve my problem?

Display all images from one directory having a prefix [Angular & Node]

I´m figuering out how to display all images in one folder with AngularJS. Problem is, I just want to get the images having the same specific prefix in their filename. The prefix always ends with a dot, e.g. 5412ec.test.jpg.

How do I display a complete folder of images in Angular? And how do I look for the prefix? I´ve tried displaying the whole folder, like this, but got a 404.

NodeJs

app.get('/uploads/', function (req, res, next){
    fs.readdir('/uploads/', function(err, files){
        if (err) return next (err);
        res.send(files);
    });
});

Angular Controller

$http.get('/uploads/').then(function (files){
    $scope.img = files;
});

Displaying images

<li ng-repeat="x in img">
    <img ng-src="x" width="150" height="100"/>
</li>

Cheers, Wandkleister.

Link to Flat-UI node_modules

I use Express 4.12.3 + JADE + flat-ui npm module (http://ift.tt/1EquvA3)

How is it possible use this module in jade?

When i run page, i get many 404 codes. I fix it with:

app.get('/e-css/flat/bootstrap.css',function(req,res) {
  res.sendFile(path.join(__dirname,'node_modules','flat-ui','bootstrap','css','bootstrap.css'));
});

In Jade:

link(rel='stylesheet', href='/e-css/flat/bootstrap.css')

I have in code many links like this.

Can be there more elegant solution?

Thank you.

formData doesn't work after getting the page with POST

I some a strange problem, when I acess to the page (with code to upload image) by GET method, everything works great. But when I access to the page with the POST method, server receive empty data.

Code:

/* ... */
var files = e.dataTransfer.files;
checkSize(files, function(s, n){
    if(s){
        var data = new FormData();
        data.append('_method', 'upload');

        $.each(files, function(k, v){
            data.append(k, v)
    });
    upload(el, data, m)
}

I think that the problem is in the upper code, buthere is the upload code:

$.ajax({
    url : $(el).parent().attr('action'),
    type: 'POST',
    data: data,
    cache: false,
    dataType:false,
    processData: false,
    contentType: false,
    success: function(data, textStatus, jqXHR){
        /* ... */
    },
    error: function(jqXHR, exception){
        /* ...*/
    }
});

Server is on nodeJs, so here is an result of receiving data after GET method:

body:
{ _method: 'upload' }
files:
{ '0':
   { fieldName: '0',
     originalFilename: 'LAYOUT.png',
     path: 'C:\\Users\\Ivan\\AppData\\Local\\Temp\\5776-1hdql6r.png',
     headers:
      { 'content-disposition': 'form-data; name="0"; filename="LAYOUT.png"',
        'content-type': 'image/png' },
     ws:
      { _writableState: [Object],
        writable: true,
        domain: null,
        _events: [Object],
        _maxListeners: 10,
        path: 'C:\\Users\\Ivan\\AppData\\Local\\Temp\\5776-1hdql6r.png',
        fd: null,
        flags: 'w',
        mode: 438,
        start: undefined,
        pos: undefined,
        bytesWritten: 349600,
        closed: true },
     size: 349600,
     name: 'LAYOUT.png',
     type: 'image/png' } }

And here, data after POST method:

body:
{ req_type: '' }
files:
undefined

angular js ng-view returns blanc partials -- Express/ Jade

I am writing an angular application following a tutorial. To my surprise, i followed exactly and my node js is starting fine without an issue. However, my angular is not returning the template as suppose to . I saw a similar problem here same tutorial and the same issue. However, the question was not answered . Below is my dir structure

app.js

var app = angular.module('app', ['ngResource', 'ngRoute']);

angular.module('app').config(function($routeProvider, $locationProvider){
    $locationProvider.html5Mode(true);
    $routeProvider
        .when('/', { templateUrl: 'partials/main', controller: 'mainCtrl'});
});


angular.module('app').controller('mainCtrl', function($scope){
    $scope.myVar = "Hello Angular";
});

My layout.jade

doctype html
head
   link(rel="styleSheet",href="css/bootstrap.css")
   link(rel="styleSheet",href="vendor/toastr/toastr.css")
   link(rel="styleSheet",href="css/site.css")
body(ng-app='app')
   block main-content
   include scripts

My main.jade

h1 This is a partial
h2 {{ myVar }}

The route in my server.js are set as

app.get('partials/:partialPath',function(req,res){
    res.render('partials/' + req.params.partialPath);
});
app.get('*', function(req,res){
    res.render('index');
});

my index.jade

extends ../includes/layout

block main-content
    section.content
       div(ng-view)

Althought i am thinking that shouldn't be an issue because i am starting with a partial view which is part of a page. When i run, my page return black. I inspect the element and ensured that all the js and css where loaded. When i view the source, a html source below was generated.

<!DOCTYPE html>
<head><link rel="styleSheet" href="css/bootstrap.css">
<link rel="styleSheet" href="vendor/toastr/toastr.css">
<link rel="styleSheet" href="css/site.css">
</head>
<body ng-app="app">
  <section class="content">
   <div ng-view></div></section>
   <script type="text/javascript" src="vendor/jquery/dist/jquery.js"></script><script type="text/javascript" src="vendor/angular/angular.js"></script>
<script type="text/javascript" src="vendor/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="vendor/angular-route/angular-route.js"></script><script type="text/javascript" src="app/app.js"></script>
</body>

I was suspecting routeProvider from my app.js here

.when('/', { templateUrl: 'partials/main', controller: 'mainCtrl'});

tried

.when('/', { templateUrl: '/partials/main', controller: 'mainCtrl'});

All to no avail . please where do i go wrong ? I have tried everything possible. I even restarted the tut yet still blanc. any help would be appreciated.

How to update html header after login in an angular/node.js application?

I am trying to get a header to update after login. I have used both $on and $watch in this effort to no avail. When I refresh it works correctly. Code is as follows below.

header.html (missing excess nav bar code for simplicity)

<li><a ng-href="#/login" ng-hide="showMenu">Login</a></li>
<li><a ng-href="#/signup" ng-hide="showMenu">Signup</a></li>
<li><a href="javascript:" ng-click="logout()" ng-show="showMenu">Logout</a></li>

app.js

$stateProvider
  .state('app', {
    url: '',
    views: {
      'header': {
            templateUrl: 'views/partials/_header.html',
            controller: 'HeaderCtrl'
      }
    }
  })

header.js (The broadcast fires correctly as demonstrated by the console.logs)

angular.module('urbinsight')
.controller('HeaderCtrl', function ($scope, $rootScope, $state, $location, UserAuthFactory, AuthFactory) {

$scope.logout = function () {
  UserAuthFactory.logout();
  $rootScope.$broadcast('loginStateChange');
  $location.path('/');
};

$scope.showMenu = AuthFactory.loggedStatus();

$rootScope.$on('loginStateChange', function(){
  console.log($scope.showMenu)
  $scope.showMenu = AuthFactory.loggedStatus(); 
  console.log($scope.showMenu)
  })
})

authService

angular.module('urbinsight.services')
.factory('AuthFactory', function ($window) {
var isLogged = false;

return {
  check: function() {
    if ($window.sessionStorage.token && $window.sessionStorage.user) {
      isLogged = true;
    } else {
      isLogged = false;
      delete this.user;
    }
  },
  loggedStatus: function() {
    return isLogged;
  },
  changeLoggedStatus: function() {
    isLogged = !(isLogged);
  }
};
})

Please tell me what I am doing wrong.

angular partial not rendering with jade

I am building an angular app following a tut. However, my angular ng-view is not rendering. I have seen a similar question here yet it has not been answered. Below is my dir structure

app.js

var app = angular.module('app', ['ngResource', 'ngRoute']);

angular.module('app').config(function($routeProvider, $locationProvider){
    $locationProvider.html5Mode(true);
    $routeProvider
        .when('/', { templateUrl: 'partials/main', controller: 'mainCtrl'});
});


angular.module('app').controller('mainCtrl', function($scope){
    $scope.myVar = "Hello Angular";
});

My layout.jade

doctype html
head
   link(rel="styleSheet",href="css/bootstrap.css")
   link(rel="styleSheet",href="vendor/toastr/toastr.css")
   link(rel="styleSheet",href="css/site.css")
body(ng-app='app')
   block main-content
   include scripts

My main.jade

h1 This is a partial
h2 {{ myVar }}

The route in my server.js are set as

app.get('partials/:partialPath',function(req,res){
    res.render('partials/' + req.params.partialPath);
});
app.get('*', function(req,res){
    res.render('index');
});

my index.jade

extends ../includes/layout

block main-content
    section.content
       div(ng-view)

Although I am thinking that shouldn't be an issue because I am starting with a partial view which is part of a page. When I run my page it returns black. I inspected the elements and ensured that all the js and css where loaded. The html source below was generated on my page:

<!DOCTYPE html>
<head><link rel="styleSheet" href="css/bootstrap.css">
<link rel="styleSheet" href="vendor/toastr/toastr.css">
<link rel="styleSheet" href="css/site.css">
</head>
<body ng-app="app">
  <section class="content">
   <div ng-view></div></section>
   <script type="text/javascript" src="vendor/jquery/dist/jquery.js"></script><script type="text/javascript" src="vendor/angular/angular.js"></script>
<script type="text/javascript" src="vendor/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="vendor/angular-route/angular-route.js"></script><script type="text/javascript" src="app/app.js"></script>
</body>

I was suspecting routeProvider from my app.js here

.when('/', { templateUrl: 'partials/main', controller: 'mainCtrl'});

tried

.when('/', { templateUrl: '/partials/main', controller: 'mainCtrl'});

All to no avail. Please where do I go wrong ? I have tried everything possible. I even restarted the tut yet still blank. Any help would be appreciated.

How to listen for Room events

So to clarify, I know the client should send a message such as 'join-room' to the server for handling, and thats fine, and I know I can do the same for 'leave-room'.

What I want is to actually listen to the events themself, because say if a client disconnects, I need to send a message to the rooms affected, as when a client disconnects then they automatically leave all rooms.

So I want something like;

socket.on('join' function() {
// send message
});

socket.on('leave' function() {
// send message
});

So that if the user closes the window (which disconnects the client, and then triggers all the rooms to be left) I can send a message out.

I am using the latest socket.io, with the redis adaptor.

Also;

What is the most efficient way to list all the rooms a particular socket is in, as technically I think the disconnect event should contain the client_id so I could do this manually.

The key thing is clarity and stability, although I am open to alternate approaches (must still use socket.io).

Thanks

How to set JSON object in variable using swig node js?

I want to set a JSON object in client side javascript using swig. I tried with json filter of swig but it just print JSON object not assign. <script type="text/javascript"> var bootstrap = "{{locals.bootstrap | json}}"</script> as we know in Javascript this bootstrap variable is globally accessible in whole the application. but I am not able to set JSON object. I tried this var bootstrap = "{{locals.bootstrap}}" refer link . but its for just any property not for json object, its just set "[object,object]" in bootstrap not json object. I tried with json filter of swig refered link , but not get succeed.

Load module using node.js require

I'm pretty new to node.js and I've been stuck for quite a long time on a problem I can't solve. I'm building a node.js app using express and jade frameworks. The app has the standard skeleton, that's how looks the main directory :

  • app.js
  • bin
  • npm-debug.log
  • views
  • node_modules
  • package.json
  • public

The problem occurs when I try to load the socket.io module in a js file (called lets say x.js) within the public directory. That's where I've implemented some logic tightly connected to user-action event handling. So in other words when someone clicks on a button 'connect', I'd like to establish connection using socket.io. The problem is that when I add this line

var socket_io = require('socket.io'); in x.js

the whole functionality suddenly stops working, I guess due to the fact that the module is not loaded although the var socket_io isn't used anywhere below within the x.js file. If I add the line var socket_io = require('socket.io'); to app.js everything works. I looked into this SO question but with no success. Can someone explain why is this happening and what am I doing wrong?

Getting "failed to start accepting connection" while deploying my app into bluemix

Hi Am facing "failed to start accepting connection" error while pushing or deploying my app to bluemix. Can any help me in that.... my code snippet as given below:

var express     = require('express');
app         = express();
var ibmbluemix  = require('ibmbluemix') 
var ibmdb = require('ibm_db');
var http = require('http');
var url = require('url');
var logger = ibmbluemix.getLogger();
var PORT = (process.env.VCAP_APP_PORT || 8000);
var HOST = (process.env.VCAP_APP_HOST || 'localhost');
var queryData = null;
var serviceName = 'SQLDB';

if (process.env.VCAP_SERVICES) {
   var env = JSON.parse(process.env.VCAP_SERVICES);
db2 = env['sqldb'][0].credentials;
 }
 else{
      console.error("INFORMATION FOR DB CONNECTION NOT FOUND");
     }

var dbConnection = "DRIVER={DB2};DATABASE=" + db2.db + ";UID=" +  db2.username + ";PWD=" + db2.password + ";HOSTNAME=" + db2.hostname +  ";port=" + db2.port;
console.log("Connection String: " + dbConnection);

http.createServer(function(request, response) {
     console.log('Creating the http server');
     ibmdb.open(dbConnection, function(err, conn) {
        if (err ) {
         response.send("error occurred " + err.message);
        }
        else {
            console.log('before select');
            conn.query("SELECT FULL_NAME,  PASSWORD,  SHORT_ID FROM USER02130.USER_DETAILS", function(err,  rows, moreResultSets) 
{
  console.log('Connection result error '+err);
            console.log('no of records is '+rows.length);
            response.writeHead(200, { 'Content-Type': 'application/json'});
            response.write(JSON.stringify(rows));
            response.end();

    } );
}
}).listen(PORT, HOST);

Can anyone help me in this, Thanks in advance

how to send an id="" to all socket in nodejs?

I have a problem with nodejs and socket.io I tried in other discussions in order to understand how to solve my problem , but I did not succeed . I'm going to create a board with score and I created a simple counter in javascript . I want to convey to all who open the ' localhost address : port with nodejs advances counter this is what I have made ​​so far

tabellone.js

    var express = require('express');
var app     = express();
var http    = require('http').Server(app);
var io      = require('socket.io')(http)

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

io.emit('some event', { for: 'everyone' });

io.on('connection',function(socket){
    socket.on('contatore', function(){
   socket.broadcast.emit('contatore', contatore);
    });
});


http.listen(3000, function(){
  console.log('listening on *:3000');
});

index.html

    <html>
<head>
  <title>tab</title>
</head>
<script src="http://ift.tt/1pV2OyR"></script>
 <script src="http://ift.tt/1pTZRh4"></script>
 <script src="/http://ift.tt/1aeIZU4"></script>
<body>
<ul id="tab"></ul> 
  <form id="form">
   <p id="contatore">0</p>
   <button id="m" type="button" 
   onClick="javascript:contatore_su();"> + </button>
   <button type="button" 
   onClick="javascript:contatore_giu();"> - </button>
   </form>
 <script>
  var s=0;
  function contatore_su() {
   s=s+1;
   document.getElementById('contatore').innerHTML = s;
 }
 function contatore_giu() {
   s=s-1;
   document.getElementById('contatore').innerHTML = s;
 }
</script>
<script>
var socket=io();
 $('form').click(function(){
   socket.emit('conteggio', $('#m').val());
    $('#m').val('');
    return false;
  });
  socket.on('conteggio', function(msg){
    $('#tab').append($('<li>').test(msg));
  });
</script>
</body>
</html>

I have previously created a chat by following what is written on socket.io but I can not convey to all connected sockets the advancement counter , thanks for the help ps. Sorry for my english :')

Express js Mongoose alternative to MySQL % Wildcard

I've been reading up and tried a few different code snippets that others have had success with, but I can't seem to get it to work.

What I'd like is for users to search using only part of the term i.e pe for 'peter'. I'd like to have a wildcard on the search term.

My code so far, which isn't working:

router.get('/:callsign', function(req,res){
var search = req.params.callsign;
var term = escape(search);
term = term.toUpperCase();
if(search=="*" || search==""){
    res.redirect("/");
}
User.find({'callsign' : new RegExp('^'+term+'$', "i") }, function(err, callsign){
    if(err)
    {
        console.log('No user found'+err);
        req.flash('message','Sorry, something went wrong. Try again.');
        res.render('callSearchResults'),{
            message: req.flash('message'), 
            title: 'Sorry, no results'
        }
    }
    if(callsign){
        console.log('Callsign:'+callsign+term);
        res.render('callSearchResults',{
            call: callsign,
            title: 'You searched for '+search,
            query: term
        });
    }else{
        console.log('No entries found'+search);
    }
});
});

Also, 'callsign' callback is constantly true - even when there are no results!

unirest content-type shows unexpected token : during execution

I am using unirest npm to access an API. Here is the code I am trying, but it gives an error "Syntax error: unexpected token : at .header('content-type': 'application/json')"

var unirest = require('unirest');
unirest.get('https://URL/index.php?/api/V2/get_case/2')
.header('content-type': 'application/json')
.auth({user:'a@b.com',
       pass:'password',
       sendImmediately:true
       })
.end(function(response){
console.log(response.body);
});

can you suggest a fix for this? thanks in advance.

Chrome extension to send data to a webpage

I want my chrome extension to send a data to my web application based on a node.js controller.

Like it's done in this question: Submitting Ajax request to node.js controller.

I have used an AJAX call to send the data and the call is successful, but I don't know how to how to pass that url being sent as a parameter to node.js app controller.

Here is my code:

google_helper.js file that is sending data.

$("body :not(#prospector-modal)").on("click", "a.add-to-prospector", function(event){
  var that = this;
  event.preventDefault();
  event.stopPropagation();
  console.log('adding');
  fetchable = $(that).data('target');
  console.log("fetchable " + fetchable.description);
  console.log("fetchable " + fetchable.url); //this is the url that i have to send


  $.ajax('http://ift.tt/1GUXMEg', {
          headers: { 'Content-Type': 'application/json'},
          data: JSON.stringify({fetchables: [fetchable] })
  }).done(function (data, textStatus, xhr) {
    debugLog("POST.done");
    debugLog(xhr);
    $(that).replaceWith("<span class='prospector-added'>Added!</span>");
    initOrReinit();
  }).fail(function (xhr, errorMessage, error) {
    debugLog("POST.fail");
    debugLog(xhr);
    if( xhr.status == 401 ) {
      displayErrorSalesLoftLoginModal();
    } else if (xhr.status == 429) {
      displayErrorLimitModal();
    } else {
      displayErrorModal();
    }
  });    
});

When I am making a request, it is going in .done part of ajax call.

background.js:

var Fetchable = function(data) {
  this.data = data;
};

Fetchable.prototype = {
  fetch: function(delay_milliseconds) {
    var self = this;
    $.get(this.data.url).done(function (data, textStatus, xhr) {
      debugLog("fetch.done");
      queue_processor.doneWorking();
      setTimeout(function() {
        queue_processor.processNext();
      }, delay_milliseconds);
      self.update({response_body: xhr.responseText, response_status: xhr.status});
    }).fail(function (xhr, errorMessage, error) {
      debugLog("fetch.fail");
      queue_processor.doneWorking();
      self.update({response_body: xhr.responseText, response_status: xhr.status});
    });
  },

  update: function(data) {
    var self = this;

    $.ajax({
      url: 'http://ift.tt/1GUXMEg',
      type: 'POST',
      data: data
    }).done(function (data, textStatus, xhr) {
      debugLog("update.done");
      setBadge(data.pending_count);
    }).fail(function (xhr, errorMessage, error) {
      console.log("update.fail: error updating fetchable "+self.data.id);
    });
  }

};
/// End Fetchable ///

Here is the controller code of my node.js app where I want to send the url to controller function:

$scope.getLinkedInData = function() {
  if(!$scope.hasOwnProperty("userprofile")){
    IN.API.Profile(/** url from the call **/).fields(
      [ "id", "firstName", "lastName", "pictureUrl",
        "publicProfileUrl","positions","location","email-address"]).result(
        function(result) {
            console.log(result);
            // ...

Build native 64bit and 32bit exe with JXCore

I'm looking for a way to builn a native 32bit exe on my 64bit developing machine.

Usually I would run: jx compile .\PhotoFly.jxp But that produces a 64bit version.

Any ideas how to get the 32bit version?

Getting 404 error while accessing my API via node js server

I am a newbie at mean stack development. I was trying to create an API for simple user registration and got stuck with a 404 error.

Here are my code files

package.json

{
  "name": "userStory",
  "version": "1.0.0",
  "description": "This is a user story App",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Arindam Dawn",
  "license": "ISC",
  "dependencies": {
    "bcrypt-nodejs": "0.0.3",
    "body-parser": "^1.12.3",
    "express": "^4.12.3",
    "mongoose": "^4.0.2",
    "morgan": "^1.5.2"
  }
}

user.js

var mongoose = require('mongoose');

var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');

var UserSchema = new Schema({

    name : String,
    username : {type: String, required: true, index: {unique: true}},
    password : {type: String, required: true, select: false}

});

UserSchema.pre('save', function(next){

    var user = this;

    if(!user.isModified('password')) return next();

    bcrypt.hash(user.password, null, null, function(err, hash){
        if(err) return next(err);

        user.password = hash;
        next();

    });

});

UserSchema.methods.comparePassword = function(password){

    var user = this;
    return bcrypt.compareSync(password, user.password);
}

module.exports = mongoose.model('User', UserSchema);

api.js

var User = require('../models/user');

var config = require('../../config');

var secretKey = config.secretKey;

module.exports = function(app, express){

    var api = express.Router();

    api.post('/signup', function(req, res){

        var user = new User({
            name: req.body.name,
            username: req.body.username,
            password: req.body.password
        });

        user.save(function(err){
            if(err){
                res.send(err);
                return;
            }

            res.json({message : 'User has been created'});
        });
    });


    return api


}

server.js

var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var config = require('./config');
var mongoose = require('mongoose');
var app = express();

mongoose.connect(config.database, function(err){
    if(err){
        console.log(err);
    }else{
        console.log("Connected to the database");
    }
});

app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
app.use(morgan('dev'));


var api = require('./app/routes/api')(app, express);
api.use('/api', api);

app.get('*', function(req, res) {
    res.sendFile(__dirname + '/public/views/index.html');
});

app.listen(config.port,function(err){
    if(err){
        console.log(err);
    }else{
        console.log("Listening on port 3000");
    }
});

config.js

 module.exports = {

    "database" : "mongodb://root:abc123@ds045531.mongolab.com:45531/userstory",
    "port" : process.env.PORT || 3000,
    "secretKey" : "addyrockz"
}

Here is my directory structure

userStory
    -app
      -models
        -user.js
      -routes
        -api.js
    -node_modules
    -public
      -index.html
    config.js
    package.json
    server.js

I am trying to check the API using postman client. I tried the url localhost:3000/api/signup using post and url-encoded.

I passed the three fields as name, username and password with their respective values but i am recieving 404 error.

Single Page Application over IIS vs Node + IIS?

We are developing a single page application using AngularJs having an index file at the root which will be served by web server to client. Currently when developing, we are using Node with express server. We need to deploy this application to azure. There are two deployment options available.

  1. Deploy either as web application on azure (I think its IIS server in this case)
  2. Or deploy on IIS using IIS Node module

We need to have a rewrite rule, which will serve index page for every other request to server in both cases.

Which is better deployment model or if anyone can suggest another option available for SPA on Azure?

Upsert an array of items with MongoDB

I've got an array of objects I'd like to insert into a MongoDB collection, however I'd like to check if each item already exists in the collection first. If it doesn't exist then insert it, if it does exist then don't insert it.

After some Googling it looks like I'm best using the update method with the upsert property set to true.

This seems to work fine if I pass it a single item, as well as if I iterate over my array and insert the items one at a time, however I'm not sure whether this is the correct way to do this, or if it's the most efficient. Here's what I'm doing at the moment:

var data = [{}, {}, ... {}];

for (var i = 0; i < data.length; i++) {

  var item = data[i];

  collection.update(
    {userId: item.id},
    {$setOnInsert: item},
    {upsert: true},
    function(err, result) {

      if (err) {
        // Handle errors here
      }

  });

}

Is iterating over my array and inserting them one-by-one the most efficient way to do this, or is there a better way?

NodeJS - Socket.io allowing only JWT verified connections

My code is that simple:

/*global require module process console*/
/*eslint-disable*/
(function (require, process) {
  'use strict';

  var config = require('../config')
  , uuid = require('node-uuid')
  , crypto = require('crypto')
  , fs = require('fs')
  , port = parseInt(process.env.PORT || config.server.port, 10)
  , serverHandler = function (req, res) {
    res.writeHead(404);
    res.end();
  }
  , httpUrl
  , io
  , server;

// Create an http(s) server instance to that socket.io can listen to
if (config.server.secure) {

  server = require('https').Server({
    'key': fs.readFileSync(config.server.key),
    'cert': fs.readFileSync(config.server.cert),
    'passphrase': config.server.password
  }, serverHandler);
} else {

  server = require('http').Server(serverHandler);
}

server.listen(port);

io = require('socket.io').listen(server);

if (config.logLevel) {
    // http://ift.tt/1GVb2Zy
    io.set('log level', config.logLevel);
  }

  function describeRoom(name) {

    var clients = io.sockets.clients(name);

    var result = {
      'clients': {}
    };

    clients.forEach(function (client) {
      result.clients[client.id] = client.resources;
    });

    return result;
  }

  function clientsInRoom(name) {

    return io.sockets.clients(name).length;
  }

  function safeCb(cb) {

    if (typeof cb === 'function') {
      return cb;
    }
  }

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

    client.resources = {
      'screen': false,
      'video': true,
      'audio': false
    };

    // pass a message to another id
    client.on('message', function (details) {

      if (!details) {

        return;
      }

      var otherClient = io.sockets.sockets[details.to];

      if (!otherClient) {

        return;
      }

      details.from = client.id;
      otherClient.emit('message', details);
    });

    client.on('shareScreen', function () {

      client.resources.screen = true;
    });

    client.on('unshareScreen', function (type) {

      client.resources.screen = false;
      removeFeed('screen');
    });

    client.on('join', join);

    function removeFeed(type) {
      if (client.room) {

        io.sockets.in(client.room).emit('remove', {
          'id': client.id,
          'type': type
        });

        if (!type) {

          client.leave(client.room);
          client.room = undefined;
        }
      }
    }

    function join(name, cb) {
        // sanity check
        if (typeof name !== 'string') {

          return;
        }
        // check if maximum number of clients reached
        if (config.rooms
          && config.rooms.maxClients > 0
          && clientsInRoom(name) >= config.rooms.maxClients) {

          safeCb(cb)('full');
        return;
      }
        // leave any existing rooms
        removeFeed();
        safeCb(cb)(null, describeRoom(name));
        client.join(name);
        client.room = name;
      }

    // we don't want to pass 'leave' directly because the
    // event type string of 'socket end' gets passed too.
    client.on('disconnect', function () {
      removeFeed();
    });
    client.on('leave', function () {
      removeFeed();
    });

    client.on('create', function (name, cb) {
      if (arguments.length == 2) {
        cb = (typeof cb == 'function') ? cb : function () {};
        name = name || uuid();
      } else {
        cb = name;
        name = uuid();
      }
        // check if exists
        if (io.sockets.clients(name).length) {
          safeCb(cb)('taken');
        } else {
          join(name);
          safeCb(cb)(null, name);
        }
      });

    // support for logging full webrtc traces to stdout
    // useful for large-scale error monitoring
    client.on('trace', function (data) {
      console.log('trace', JSON.stringify(
        [data.type, data.session, data.prefix, data.peer, data.time, data.value]
        ));
    });


    // tell client about stun and turn servers and generate nonces
    client.emit('stunservers', config.stunservers || []);

    // create shared secret nonces for TURN authentication
    // the process is described in draft-uberti-behave-turn-rest
    var credentials = [];

    config.turnservers.forEach(function (server) {

      var hmac = crypto.createHmac('sha1', server.secret);
        // default to 86400 seconds timeout unless specified
        var username = Math.floor(new Date().getTime() / 1000) + (server.expiry || 86400) + '';

        hmac.update(username);

        credentials.push({
          'username':username,
          'credential':hmac.digest('base64'),
          'url':server.url
        });
      });
    client.emit('turnservers', credentials);
  });

if (config.uid) {

  process.setuid(config.uid);
}

if (config.server.secure) {

  httpUrl = 'https://localhost:' + port;
} else {

  httpUrl = 'http://localhost:' + port;
}

console.info('Signaling WS is running at:' + httpUrl);
/*eslint-enable*/
}(require, process));

What i would like is just to allow ONLY jwt verified connections on socket.io, how can i do?

Practially i would stop any not jwt authenticated user to connect on socket.io...

Users are signed through the express-jwt expressJWT.sign(userProfile, config.secretKey) method

Any help appreciated thanks!

Gulp command opens gulp.js in notepad instead of running it

I did install it correctly i think.

My package.json

   {
      "name": "my-project",
      "version": "0.1.0",
      "devDependencies": {
        "gulp": "^3.8.11",
        "gulp-concat": "^2.5.2"
      }
    }

my gulp.js

var gulp = require('gulp');

    var concat = require('gulp-concat');

    gulp.task('scripts', function() {
        return gulp.src('js/*.js')
          .pipe(concat('main.js'))
          .pipe(gulp.dest('build/js'));
    });

    gulp.task('default', ['scripts']);

my folder are as follow :

ROOT/package.json
ROOT/gulp.js
ROOT/node-modules/   <-- my modules are here
ROOT/js/  <-- my js are here

When I run gulp in command line, being in the ROOT folder, gulp.js just opens in windows notepad and thats all..

Why is it doing that ?

Also this might be terribly stupid from me but I'm not actually running a local server. I dont have wamp installed on this computer. Just figured it might be a problem for node.js

Nodejs - incorporate HTML files

I'm super new to NodeJS and I'm using it for a small college project. The project itself is a Unity based game and as part of this project I need to build a small website for it.

I've created a few HTML files (homepage,about,download page,registration form).

I know I can use:

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(3000);

But this just displays one line of text.

I would like to link all of these pages or set the homepage using Nodejs. Can you please let me know how I can do that?

Thanks in advance.

Watch window or evaluate expressions while debugging in VS Code?

I really like Visual Studio Code, it's a great editor but one thing is really annoying me while debugging Node apps:

I can't see any sort of watch window or the ability to evaluate expressions while debugging. This makes debugging pretty painful and I'm considering moving back to VS 2013.

I know we have the local and global variables windows but they are a pain to look through (maybe add a search box?) and some things just don't appear in the list.

For example using TypeScript, a class function compiles down to something like this:

Stack.prototype.push = function (item) {
    if (this.items.length == this.length)
        this.resize(length * 2);
    this.items[this.length++] = item;
};

When debugging this function however I don't have any access to the this variable while in the push() function. It does not appear in either the local or global variables and I can't evaluate it anywhere.

Has anyone else experienced this and found a solution?

Menu not displaying on node-webkit

Everyone!
I was working on a small project and i came across to this situation. One of my friend suggested me of using menu. I used following code as sample.

    <script>
    var gui = require('nw.gui'), db = require('diskdb'), fs = require("fs"), path = require('path');
    var win = gui.Window.get();     
    var menu = new gui.Menu();
    var info_item = new gui.MenuItem({ label: 'Which Fruit Do I Love?' });
    menu.append(info_item);
    menu.popup(500, 20);        
    var process = false, scr = 0, directory, w, h, ratio,canvas, base_, files_   = new Array(), files = new Array();
    db = db.connect("lib/collections", ['libery', 'temp']);
    .
    .
    </script>

It worked.And I thought lets try other way. So I added a little code at the bottom. But as soon as I changed code to this:

<script src="js/jquery.min.js"></script>
<script>
    var gui = require('nw.gui'), db = require('diskdb'), fs = require("fs"), path = require('path');
    var win = gui.Window.get();     
    var menu = new gui.Menu();
    var info_item = new gui.MenuItem({ label: 'Which Fruit Do I Love?' });
    menu.append(info_item);     
    var process = false, scr = 0, directory, w, h, ratio,canvas, base_, files_   = new Array(), files = new Array();
    db = db.connect("lib/collections", ['libery', 'temp'])
    $('body').on('contextmenu', function(ev) { 
        ev.preventDefault();
        menu.popup(ev.x, ev.y);
        return false;
    });
</script>

Then I got error saying following:

Uncaught node.js Error

TypeError: undefined is not a function
at Menu.popup (menu.js:69:6)
at HTMLBodyElement.<anonymous> (file:///E:/projects/desktop%20app/lib/protype.html:138:10)
at HTMLBodyElement.x.event.dispatch (file:///E:/projects/desktop%20app/lib/js/jquery.min.js:5:9843)
at HTMLBodyElement.y.handle (file:///E:/projects/desktop%20app/lib/js/jquery.min.js:5:6633)

Then later i kept everything same and just moved of line of code below like this:

  <script>
    ....
    ....
    var process = false, scr = 0, directory, w, h, ratio,canvas, base_, files_   = new Array(), files = new Array();
    db = db.connect("lib/collections", ['libery', 'temp']);    
    var menu = new gui.Menu();
    var info_item = new gui.MenuItem({ label: 'Which Fruit Do I Love?' });
    menu.append(info_item);    
    $('body').on('contextmenu', function(ev) { ...
    ....
  </script>

And now amazing thing is it again gave error as bellow:

Uncaught node.js Error##

TypeError: undefined is not a function
at new Menu (menu.js:32:6) at file:///E:/projects/desktop%20app/lib/protype.html:134:14

I dont get it. Whats wrong with my code? I don't understand why does it says error. I have read the menu docs and I think there isn't anything wrong with my code. If there is then please do help me. And If anyone can please explain win in earth I am getting these error. Thank you.

Is application change required when new couchbase node added to cluster?

I am using Node.js SDK to connect to a couchbase cluster. In Node.js docs they haven't specified how to pass multiple ips(of cluster nodes) while creating the cluster object but java docs shows it can accept array of IPs, is this functionality available in Node.js SDK too?

Also if this is how you connect to cluster with many nodes, whenever we add new nodes to cluster do we need to add its IP to the connection string and restart the application?

PS I am new to Couchbase and Node.js so please bear with me

Execute UPNP on Web Browser using Jquery/Javascript

I want to search and add gateways in my local network using UPNP protocol such that when a user log in the web application, a UPNP service is run on page load and he gets a list of all the available gateways through that.

For this I'm looking a library to implement the same on client side.

My questions are: 1. Is it safe to perform this search on client side? 2. I found a library: http://ift.tt/1dTC1hp, this library is for node.js, how to implement it on client?

Port no. For Web socket when using stormpath

so I have a node. js Web application built using express.on this app I pass custom data to the node server using socket.io and it's then supposed to save in a the associated user account. When I was testing this locally it worked fine but since I've launched it the socket is no longer working. I think I may be using the wrong port number for the socket or else am I just doing this completely wrong?? Thank you in advance

How to create a bill system with Node.js and front-end angular.js

How to create my first any billing system application by users node.js and angular js

npm request with headers and auth

I am trying to access an API using "request" npm. This API requires header "content-type" and a basic authentication. here is what I've done so far.

var request = require('request');
var options = {
  url: 'https://XXX/index.php?/api/V2/get_case/2',
  headers: {
    'content-type': 'application/json'
  },

};
request.get(options, function(error, response, body){
console.log(body);
}

).auth("dummyemail@abc.com","password",false);

upon executing this using Node , I am getting an error that says invalid username and password. I've validated the same API, authentication and header using CURL with the command below and it gave an expected HTTP response.

curl -X GET -H "content-type: application/json" -u dummyemail@abc.com:password "https://XXX/index.php?/api/V2/get_case/2"

Please suggest the right way to code request with auth and header.

Nodejs many http request callback

I have to request to multi http request, and wait all callback to update result. I 'm using jxcore to make it workby multi thread, and by multi pc. Any idea how to improve it ? I'm using async.each to execute 5000 url each task. I have about 100000 urls to request , and it wasted about 3h to finish (on 1 pc)

Node.js Express install No README data

I am totally brandnew to node.js and trying to install the express framework, not very sure why when i install Express by

$ npm express install --save

it gives me this package.json test@1.0.0 No README data then lots of ERR!

Thanks

Debug log

0 info it worked if it ends with ok
1 verbose cli [ 'node', '/usr/local/bin/npm', 'install', 'express', '--save' ]
2 info using npm@2.7.4
3 info using node@v0.12.2
4 warn package.json test@1.0.0 No README data
5 silly cache add args [ 'express', null ]
6 verbose cache add spec express
7 silly cache add parsed spec { raw: 'express',
7 silly cache add   scope: null,
7 silly cache add   name: 'express',
7 silly cache add   rawSpec: '',
7 silly cache add   spec: '*',
7 silly cache add   type: 'range' }
8 verbose addNamed express@*
9 silly addNamed semver.valid null
10 silly addNamed semver.validRange *
11 silly addNameRange { name: 'express', range: '*', hasData: false }
12 silly mapToRegistry name express
13 silly mapToRegistry using default registry
14 silly mapToRegistry registry http://ift.tt/1bx8DsD
15 silly mapToRegistry uri http://ift.tt/1iluc3i
16 verbose addNameRange registry:http://ift.tt/1iluc3i not in flight; fetching
17 verbose request uri http://ift.tt/1iluc3i
18 verbose request no auth needed
19 info attempt registry request try #1 at 3:02:08 PM
20 verbose request id 42abc9c7545a84ee
21 verbose etag "5QPC4D9F40JTXPEZQJQJ5L09D"
22 http request GET http://ift.tt/1iluc3i
23 http 304 http://ift.tt/1iluc3i
24 silly get cb [ 304,
24 silly get   { date: 'Sat, 09 May 2015 07:02:18 GMT',
24 silly get     via: '1.1 varnish',
24 silly get     'cache-control': 'max-age=60',
24 silly get     etag: '"5QPC4D9F40JTXPEZQJQJ5L09D"',
24 silly get     age: '36',
24 silly get     connection: 'keep-alive',
24 silly get     'x-served-by': 'cache-hkg6823-HKG',
24 silly get     'x-cache': 'HIT',
24 silly get     'x-cache-hits': '1',
24 silly get     'x-timer': 'S1431154938.074288,VS0,VE2',
24 silly get     vary: 'Accept' } ]
25 verbose etag http://ift.tt/1iluc3i from cache
26 verbose get saving express to /Users/clarkho/.npm/http://ift.tt/1JxrsdK

Log from Terminal

npm WARN package.json test@1.0.0 No README data
npm ERR! Darwin 12.5.0
npm ERR! argv "node" "/usr/local/bin/npm" "install" "express" "--save"
npm ERR! node v0.12.2
npm ERR! npm  v2.7.4
npm ERR! path /Users/clarkho/.npm/debug/2.1.3
npm ERR! code EACCES
npm ERR! errno -13

npm ERR! Error: EACCES, mkdir '/Users/clarkho/.npm/debug/2.1.3'
npm ERR!     at Error (native)
npm ERR!  { [Error: EACCES, mkdir '/Users/clarkho/.npm/debug/2.1.3']
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/Users/clarkho/.npm/debug/2.1.3',
npm ERR!   parent: 'express' }
npm ERR! 
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/clarkho/Localhost/nodeapp/npm-debug.log

vendredi 8 mai 2015

How to run Socket.io Chat Demo? Error on ..//

Hello I am new to programming and was trying to run the socket.io chat demo. However, when I try running it it gives me a error which is found at line 5 saying it can't find ('../..'). Can someone explain to me why this is happening?

Heres a snippet of the code where the issue is at:

// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('../..')(server);
var port = process.env.PORT || 3000;

server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

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

// Chatroom

The source code of the full thing is on Github

A weird Error object is being logged to console

I am trying to post comments through the youtube API, but they are returning an error upon trying.

When I log the error object I get

{ [Error: Bad Request] code: 400 }

The first part of which looks weird (key-value inside array?)

I tried to log the keys of the object and it only returns code

Supposely the API return a much more detailed message, but it's like it's 'hidden' inside the [Error: Bad Request], which I dont know how to access

Request in nodejs: Not redirecting

Request module in nodejs is supposed to automatically redirect URL once it receives redirect code: 302 right? It is not redirecting and my app is receiving a status code=200 with the cookies not set. What can I set so that redirection is automatic thanks!

How to cancel a stream if browser cancels his request ? Which event

In my browser I display a lot of thumbs. If a thumb is not visible (out of the viewport), I set the src to '' (empty string). And when it is in the viewPort I set the correct src.

If the user uses his scrollbar, then the download of the thumbs that are not downloaded yet are canceled by the browser.

But on the server side, some of the requests becomes 'zombie' and can fill the sockets pool (maxSockets). After the timeout, the server will kill those sockets and the pile of un-downloaded thumbs restarts.

So I need to detect that a request is canceled by the Browser in order to end response. I tried many events, without result.

function(req, res) {
  var stream;
  stream = getThumb(req.file.binary.thumb);
  req.on('close', function() {
    return console.log("reQ.on close");
  });
  req.connection.on('close', function() {
    return console.log('reQ.connection.on close');
  });
  req.on('end', function() {
    return console.log('reQ.on end');
  });
  res.on('close', function() {
    return console.log("reS.on close");
  });
  res.connection.on('close', function() {
    return console.log('reS.connection.on close');
  });
  res.on('end', function() {
    return console.log('reS.on end');
  });
  stream.on('close', function() {
    return console.log('stream.on close');
  });
  return stream.pipe(res);
};

What is the event to listen to ?

note : I am using express, but it should make no difference.

cheers !

Node.js event loop confusion

Let me explain my concept first, Event loop is a single thread whose job is to register and trigger callbacks and callback are run on a separate thread i.e in Node process event loop is a thread and another thread for executing callbacks. If I am right until now, then why do a cpu intensive task block the event loop ? In case, if event loop waits for callbacks to finish and then trigger next event, how will it be asynchronous, because it waits for every callback to finish. Any nice explanation will be appreciated