Saturday, 18 March 2017

Live compiling Typescript to es5 and immediate run

So recently I've decided to try to rewrite one of my "little" projects from es5 to Typescript. It's a Node.js Rest api based on express.js.

Is there a way how to recompile a TS project into a single file on change and primarily also run the app?

When using react/es6 I'm using webpack dev server, which can recompile on change pretty quickly. When using es5 in node.js I'm using nodemon, which immediately re-runs the code on change. But how to properly combine these two functionalities? Should I use webpack to compile TS code? But is webpack capable of also running the code?

I've seen an example of using the ts compiler with nodemon, but using this way it's not possible to create one single output bundle.

src
  |- entryPoint.ts
  |- routes
  |    |- foo.ts
  |    |- bar.ts
  |    |- ...
  |- schemas
  |    |- foo.ts
  |    |- bar.ts
  |    |- ...
  |- ...
dist
  |- singleOutputBundle.js
tsconfig.json
nodemon.json
webpack.config.js
package.json



via Patrik Šimunič

Grunt task automation for multiple environments

Here is my grunt file which is not showing error but not working properly, if i remove dev and prod from 'string-replace' and have only one 'string-replace', then its work.Suggest any solution for multiple environmet.

//Gruntfile.js

module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

    'string-replace': {
        dev : {
            inline: {
                files: {
                    'index.html':'index.html'
                },
                options: {
                    replacements: [
                        {
                            pattern: '<!--start PROD imports-->',
                            replacement: '<!--start PROD imports'
                        },
                        {
                            pattern: '<!--end PROD imports-->',
                            replacement: 'end PROD imports-->'
                        },
                        {
                            pattern: '<!--start DEV imports',
                            replacement: '<!--start DEV imports-->'
                        },
                        {
                            pattern: 'end DEV imports-->',
                            replacement: '<!--end DEV imports-->'
                        }
                        ]
                }
            }
        },
        prod : {
            inline: {
                files: {
                    'index.html':'index.html'
                },
                options: {
                    replacements: [
                        {
                            pattern: '<!--start PROD imports',
                            replacement: '<!--start PROD imports-->'
                        },
                        {
                            pattern: 'end PROD imports-->',
                            replacement: '<!--end PROD imports-->'
                        },
                        {
                            pattern: '<!--start DEV imports-->',
                            replacement: '<!--start DEV imports'
                        },
                        {
                            pattern: '<!--end DEV imports-->',
                            replacement: 'end DEV imports-->'
                        }
                        ]
                }
            }
        }
    }
});
    grunt.loadNpmTasks('grunt-string-replace');

    grunt.registerTask('default', ['string-replace:dev']);
    grunt.registerTask('prod', ['string-replace:prod']);
};

I need to have it for dev and production both.



via Shubham Tripathi

AMQP (Node.js) for RabbitMQ close connection too early.

I have the following code, and it's giving me the following error.

TypeError: Cannot read property 'assertQueue' of undefined
    at /var/www/myapp/dashboard/routes.js:195:39
    at /var/www/myapp/node_modules/amqplib/lib/callback_model.js:46:16
    at /var/www/myapp/node_modules/amqplib/lib/callback_model.js:61:10
    at /var/www/myapp/node_modules/amqplib/lib/callback_model.js:74:5

If I comment out conn.close(), and the code works fine, and I think the code is trying to close the conn too early, before the execution of ch.assertQueue. What is the best way to fix this problem?

 amqp.connect('amqp://localhost', function(err, conn) {
                                  conn.createChannel(function(err, ch) {
                                    var q = 'blast_queue';
                                    var msg = blast.id;

                                    ch.assertQueue(q, {durable: true});
                                    ch.sendToQueue(q, new Buffer(msg), {persistent: true});
                                    console.log(" [x] Sent '%s'", msg);
                                  });
                                  conn.close();
  });



via user1187968

where should i place node js application on a webhosting website and can i run it the same way i run php pages?

i have a web hosting package on https://www.ecowebhosting.co.uk/ and when i develop websites and web apps using php i just place the .php files and all website files in the public_html folder in the web hosting package files and just type the URL of the php file and everything runs but with node js i run the web app from the command line on my pc , my question is after finishing the web app can i deploy it on https://www.ecowebhosting.co.uk/ using a web hosting package and if it is possible how do i do it ???



via Mohamed Nagah

Include files in a .ejs file

I am trying to use Express for my Node.js server. I put my web page in /views/page.ejs as required. Yet, I have something like this in my code.

<script type="text/javascript" src="jsfile1.js"></script>
<script type="text/javascript" src="jsfile2.js"></script>
<script type="text/javascript" src="jsfile3.js"></script>
<script type="text/javascript" src="jsfile4.js"></script>

I also have a .css file to load. My question is: how to load them ? I encounter 404 errors. My files are in the same directory as server.js (the Node.js app that I am running).

Thank you for your answers!

Noël.



via Noël Nadal

Serverless framework with aws lambda error "Cannot find module"

I'm trying to use the serverless framework to create lambda function that uses open weather npm module. However, I'm getting the following exception, but my node_modules contain a specific library. I'm quite new to serverless and node. I have managed to run the sample, (https://github.com/serverless/examples/tree/master/aws-node-rest-api-with-dynamodb) successfully, now hacking to add node module to integrate open weather api. Thanks in advance.

 Endpoint response body before transformations: {"errorMessage":"Cannot find module 'Openweather-Node'","errorType":"Error","stackTrace":["Module.require (module.js:353:17)","require (internal/module.js:12:17)","Object.<anonymous> (/var/task/todos/weather.js:4:17)","Module._compile (module.js:409:26)","Object.Module._extensions..js

My code

'use strict';

  const AWS = require('aws-sdk'); // eslint-disable-line import/no-extraneous-dependencies
  var weather = require('Openweather-Node');

  const dynamoDb = new AWS.DynamoDB.DocumentClient();

  module.exports.weather = (event, context, callback) => {
    const params = {
      TableName: process.env.DYNAMODB_TABLE,
      Key: {
        id: event.pathParameters.id,
      },
    };

    weather.setAPPID("mykey");
//set the culture
    weather.setCulture("fr");
//set the forecast type
    weather.setForecastType("daily");

    const response = {
      statusCode: 200,
      body: "{test response}",
    };
    callback(null, response);

    // weather.forecast({method: 'cityID', lang: 'fr', units: 'metric'}, function(err, data) {
    //   if (!err) {
    //     console.log(data);
    //     const response = {
    //       statusCode: 200,
    //       body: data,
    //     };
    //     callback(null, response);
    //
    //   } else {
    //     console.error(err.message);
    //   }
    //
    // });


    // fetch todo from the database
    // dynamoDb.get(params, (error, result) => {
    //   // handle potential errors
    //   if (error) {
    //     console.error(error);
    //     callback(new Error('Couldn\'t fetch the todo item.'));
    //     return;
    //   }
    //
    //   // create a response
    //   // const response = {
    //   //   statusCode: 200,
    //   //   body: JSON.stringify(result.Item),
    //   // };
    //   // callback(null, response);
    // });
  };



via Charith

How to find the roots of several trees within one object

I have a series of messages which contain unique numerical IDs, unique IDs and non-unique "in reply to" fields that reference other messages. From this object, I'm trying to find the roots of all of the trees, as well as all of the children corresponding to those trees. I've found it relatively easy to return an object containing a series of nodes with their corresponding children, but I'm having trouble merging them in an efficient way. Unfortunately, this tree could be thousands of levels deep, or just one level which makes the task considerably harder.

let exampleTree = {
  1: {
    'ID': 'IDONE',
    'IN_REPLY_TO': undefined    
  },
  3: {
    'ID': 'IDTHREE',
    'IN_REPLY_TO': 'IDONE'
  },
  7: {
    'ID': 'IDSEVEN',
    'IN_REPLY_TO': 'IDTHREE'
  },
  8: {
    'ID': 'IDEIGHT',
    'IN_REPLY_TO': 'IDTHREE'
  }
}

// should return { 1: [3, 7, 8] }

function generateMap(tree) {
  let convert = {}
  let mapped = {}
  for (let id in tree) {
    if (typeof tree[id].IN_REPLY_TO != 'undefined') {
      if (typeof mapped[tree[id].IN_REPLY_TO] != 'undefined') {
        mapped[tree[id].IN_REPLY_TO].push(tree[id].ID)
      } else {
        mapped[tree[id].IN_REPLY_TO] = [tree[id].ID]
      }
    }
    convert[tree[id].ID] = id
  }
  let uidMapped = {}
  for (let id in mapped) {
    uidMapped[convert[id]] = mapped[id].map(function(value) { return convert[value] })
  }
  return uidMapped
}

console.log(generateMap(exampleTree))

// currently returns { 1: [3], 3: [7, 8] }

Hopefully, the example above makes it clear what I'm trying to accomplish. Seven and eight are both children of three, which in turn is a child of one. I'm trying to combine these two together.



via Popey Gilbert

Express - call require once for many routes

My project directory looks something like this:

MyProject
    -app.js
    -routes
        -routeone
        -routetwo

Inside of my app.js file it looks like this:

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

var routeone = require('./routes/routeone');
var routetwo = require('./routes/routetwo');

app.use('/routeone', routeone);
app.use('/routetwo', routetwo);
.
.
.

Each route file looks something like this:

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({
    extended: false
});

router.post('/', urlencodedParser, function(req, res, next) {
    if (!req.body.param) {
        //no parameter was provided
    } else {
        //there was a parameter provided
    }
});

module.exports = router;

As you can see I have a dependency on the bodyparser module. I need to call this module in every route and specify the options for this.I may have many more routes in the future. I would like to avoid specifying this in every single route file because say I need to change the extended:true in the future I will have to go to every file and change this. I would prefer to have this in one location. I tried adding this to to the app.js file, but then urlencodedParser can;t be found inside of the route files. I also assume this has a performance hit since every route needs to load this module.



via user2924127

Karma + Angular1: window.angular.$$csp is not a function

I am trying to write tests for an Angular 1.6 app using Karma and Jasmine, as well as karma-wiredep to load the Bower dependencies - at the moment it only contains Angular 1.6.3. When I try to run karma start I am able to see the dependencies loading however both Chrome and PhantomJS fail even without loading my application/test code so I assume the problem is with the Karma configuration - the logs do show that angular.js is loading. The errors for both are similar with PhantomJS reporting WARNING: Tried to load angular more than once. however I don't see that happening in the logs. Is there a problem with that way that Karma is configured?

Chrome 57.0.2987 (Mac OS X 10.12.3) ERROR Uncaught TypeError: window.angular.$$csp is not a function at bower_components/angular/angular.js:33345

PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR TypeError: undefined is not a constructor (evaluating 'window.angular.$$csp()') at bower_components/angular/angular.js:33345

PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR TypeError: undefined is not a constructor (evaluating 'angular.module('ngAnimateMock', ['ng']) .info({ angularVersion: '1.6.3' })') at bower_components/angular-mocks/angular-mocks.js:800

karma.conf.js

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['wiredep', 'ng-scenario', 'jasmine'],

    //you can configure wiredep from here (optional) 
    wiredep: {
        dependencies: true,    // default: true  
        devDependencies: true, // default: false  
    },

    // list of files / patterns to load in the browser
    files: [
    ],

    // list of files to exclude
    exclude: [
    ],

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_DEBUG,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    // browsers: ['Chrome', 'Firefox', 'Safari', 'PhantomJS', 'IE'],
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}

bower.json

{
  "name": "app-name",
  "main": "script.js",
  "version": "0.0.1",
  "homepage": "",
  "authors": [],
  "description": "",
  "keywords": [],
  "license": "",
  "ignore": [],
  "dependencies": {
    "angular": "^1.6.3"
  },
  "devDependencies": {
    "angular-mocks": "~1.6.x"
  }
}

chrome log output

> karma start karma.conf.js
18 03 2017 15:45:22.180:DEBUG [config]: autoWatch set to false, because of singleRun
18 03 2017 15:45:22.185:DEBUG [plugin]: Loading karma-* from /path/to/app/node_modules
18 03 2017 15:45:22.187:DEBUG [plugin]: Loading plugin /path/to/app/node_modules/karma-babel-preprocessor.
18 03 2017 15:45:22.550:DEBUG [plugin]: Loading plugin /path/to/app/node_modules/karma-chrome-launcher.
18 03 2017 15:45:22.554:DEBUG [plugin]: Loading plugin /path/to/app/node_modules/karma-jasmine.
18 03 2017 15:45:22.555:DEBUG [plugin]: Loading plugin /path/to/app/node_modules/karma-ng-html2js-preprocessor.
18 03 2017 15:45:22.556:DEBUG [plugin]: Loading plugin /path/to/app/node_modules/karma-ng-scenario.
18 03 2017 15:45:22.556:DEBUG [plugin]: Loading plugin /path/to/app/node_modules/karma-phantomjs-launcher.
18 03 2017 15:45:22.586:DEBUG [plugin]: Loading plugin /path/to/app/node_modules/karma-wiredep.
18 03 2017 15:45:22.686:DEBUG [web-server]: Instantiating middleware
18 03 2017 15:45:22.764:INFO [karma]: Karma v1.5.0 server started at http://0.0.0.0:9876/
18 03 2017 15:45:22.764:INFO [launcher]: Launching browser Chrome with unlimited concurrency
18 03 2017 15:45:22.779:INFO [launcher]: Starting browser Chrome
18 03 2017 15:45:22.780:DEBUG [temp-dir]: Creating temp dir at /var/folders/84/81q1wl5d5k58flxbpcgqq78w0000gn/T/karma-67345543
18 03 2017 15:45:22.780:DEBUG [launcher]: /Applications/Google Chrome.app/Contents/MacOS/Google Chrome --user-data-dir=/var/folders/84/81q1wl5d5k58flxbpcgqq78w0000gn/T/karma-67345543 --no-default-browser-check --no-first-run --disable-default-apps --disable-popup-blocking --disable-translate --disable-background-timer-throttling --disable-device-discovery-notifications http://localhost:9876/?id=67345543
18 03 2017 15:45:23.538:DEBUG [web-server]: serving: /path/to/app/node_modules/karma/static/client.html
18 03 2017 15:45:23.557:DEBUG [web-server]: serving: /path/to/app/node_modules/karma/static/karma.js
18 03 2017 15:45:23.751:DEBUG [karma]: A browser has connected on socket 358rR6cCQQIt8Y11AAAA
18 03 2017 15:45:23.753:DEBUG [web-server]: serving: /path/to/app/node_modules/karma/static/favicon.ico
18 03 2017 15:45:23.762:DEBUG [web-server]: upgrade /socket.io/?EIO=3&transport=websocket&sid=358rR6cCQQIt8Y11AAAA
18 03 2017 15:45:23.808:INFO [Chrome 57.0.2987 (Mac OS X 10.12.3)]: Connected on socket 358rR6cCQQIt8Y11AAAA with id 67345543
18 03 2017 15:45:23.809:DEBUG [launcher]: Chrome (id 67345543) captured in 1.045 secs
18 03 2017 15:45:23.837:DEBUG [middleware:karma]: custom files null null null
18 03 2017 15:45:23.837:DEBUG [middleware:karma]: Serving static request /context.html
18 03 2017 15:45:23.839:DEBUG [web-server]: serving: /path/to/app/node_modules/karma/static/context.html
18 03 2017 15:45:23.856:DEBUG [middleware:source-files]: Requesting /base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d /
18 03 2017 15:45:23.856:DEBUG [middleware:source-files]: Fetching /path/to/app/node_modules/jasmine-core/lib/jasmine-core/jasmine.js
18 03 2017 15:45:23.857:DEBUG [web-server]: serving (cached): /path/to/app/node_modules/jasmine-core/lib/jasmine-core/jasmine.js
18 03 2017 15:45:23.859:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-jasmine/lib/boot.js?945a38bf4e45ad2770eb94868231905a04a0bd3e /
18 03 2017 15:45:23.859:DEBUG [middleware:source-files]: Fetching /path/to/app/node_modules/karma-jasmine/lib/boot.js
18 03 2017 15:45:23.859:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-jasmine/lib/adapter.js?7a813cc290d592e664331c573a1a796192cdd1ad /
18 03 2017 15:45:23.859:DEBUG [middleware:source-files]: Fetching /path/to/app/node_modules/karma-jasmine/lib/adapter.js
18 03 2017 15:45:23.860:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-ng-scenario/lib/angular-scenario.js?df746e558e332348ff12e0f08ddae4697abef3cd /
18 03 2017 15:45:23.860:DEBUG [middleware:source-files]: Fetching /path/to/app/node_modules/karma-ng-scenario/lib/angular-scenario.js
18 03 2017 15:45:23.861:DEBUG [web-server]: serving (cached): /path/to/app/node_modules/karma-jasmine/lib/boot.js
18 03 2017 15:45:23.861:DEBUG [web-server]: serving (cached): /path/to/app/node_modules/karma-jasmine/lib/adapter.js
18 03 2017 15:45:23.862:DEBUG [web-server]: serving (cached): /path/to/app/node_modules/karma-ng-scenario/lib/angular-scenario.js
18 03 2017 15:45:23.872:DEBUG [middleware:source-files]: Requesting /base/bower_components/angular-mocks/angular-mocks.js?428e663e720ed137f3931dc4e4079d00eb339620 /
18 03 2017 15:45:23.872:DEBUG [middleware:source-files]: Fetching /path/to/app/bower_components/angular-mocks/angular-mocks.js
18 03 2017 15:45:23.873:DEBUG [middleware:source-files]: Requesting /base/bower_components/angular/angular.js?367ccb6484896d3b163b691390f735bfca5cf17e /
18 03 2017 15:45:23.873:DEBUG [middleware:source-files]: Fetching /path/to/app/bower_components/angular/angular.js
18 03 2017 15:45:23.873:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-ng-scenario/lib/adapter.js?88d12e473235d74e75f0db6cbd01396f5aa58e7b /
18 03 2017 15:45:23.874:DEBUG [middleware:source-files]: Fetching /path/to/app/node_modules/karma-ng-scenario/lib/adapter.js
18 03 2017 15:45:23.875:DEBUG [web-server]: serving (cached): /path/to/app/bower_components/angular-mocks/angular-mocks.js
18 03 2017 15:45:23.877:DEBUG [web-server]: serving (cached): /path/to/app/bower_components/angular/angular.js
18 03 2017 15:45:23.890:DEBUG [web-server]: serving (cached): /path/to/app/node_modules/karma-ng-scenario/lib/adapter.js
18 03 2017 15:45:23.892:DEBUG [web-server]: serving: /path/to/app/node_modules/karma/static/context.js
Chrome 57.0.2987 (Mac OS X 10.12.3) ERROR
  Uncaught TypeError: window.angular.$$csp is not a function
  at bower_components/angular/angular.js:33345


18 03 2017 15:45:24.094:DEBUG [karma]: Run complete, exiting.
18 03 2017 15:45:24.094:DEBUG [launcher]: Disconnecting all browsers
18 03 2017 15:45:24.452:DEBUG [launcher]: Process Chrome exited with code 0
18 03 2017 15:45:24.452:DEBUG [temp-dir]: Cleaning temp dir /var/folders/84/81q1wl5d5k58flxbpcgqq78w0000gn/T/karma-67345543
18 03 2017 15:45:24.482:DEBUG [launcher]: Finished all browsers

phantomjs log output

> karma start
    18 03 2017 15:43:45.349:DEBUG [config]: autoWatch set to false, because of singleRun
18 03 2017 15:43:45.354:DEBUG [plugin]: Loading karma-* from /path/to/app/node_modules
18 03 2017 15:43:45.357:DEBUG [plugin]: Loading plugin /path/to/app/node_modules/karma-babel-preprocessor.
18 03 2017 15:43:45.735:DEBUG [plugin]: Loading plugin /path/to/app/node_modules/karma-chrome-launcher.
18 03 2017 15:43:45.739:DEBUG [plugin]: Loading plugin /path/to/app/node_modules/karma-jasmine.
18 03 2017 15:43:45.739:DEBUG [plugin]: Loading plugin /path/to/app/node_modules/karma-ng-html2js-preprocessor.
18 03 2017 15:43:45.740:DEBUG [plugin]: Loading plugin /path/to/app/node_modules/karma-ng-scenario.
18 03 2017 15:43:45.741:DEBUG [plugin]: Loading plugin /path/to/app/node_modules/karma-phantomjs-launcher.
18 03 2017 15:43:45.769:DEBUG [plugin]: Loading plugin /path/to/app/node_modules/karma-wiredep.
18 03 2017 15:43:45.880:DEBUG [web-server]: Instantiating middleware
18 03 2017 15:43:45.969:INFO [karma]: Karma v1.5.0 server started at http://0.0.0.0:9876/
18 03 2017 15:43:45.970:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
18 03 2017 15:43:45.980:INFO [launcher]: Starting browser PhantomJS
18 03 2017 15:43:45.981:DEBUG [temp-dir]: Creating temp dir at /var/folders/84/81q1wl5d5k58flxbpcgqq78w0000gn/T/karma-75656583
18 03 2017 15:43:45.984:DEBUG [launcher]: /path/to/app/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs /var/folders/84/81q1wl5d5k58flxbpcgqq78w0000gn/T/karma-75656583/capture.js
18 03 2017 15:43:47.236:DEBUG [web-server]: serving: /path/to/app/node_modules/karma/static/client.html
18 03 2017 15:43:47.246:DEBUG [web-server]: serving: /path/to/app/node_modules/karma/static/karma.js
18 03 2017 15:43:47.290:DEBUG [karma]: A browser has connected on socket qu27-ez-B1uzsqMHAAAA
18 03 2017 15:43:47.295:DEBUG [web-server]: upgrade /socket.io/?EIO=3&transport=websocket&sid=qu27-ez-B1uzsqMHAAAA
18 03 2017 15:43:47.330:INFO [PhantomJS 2.1.1 (Mac OS X 0.0.0)]: Connected on socket qu27-ez-B1uzsqMHAAAA with id 75656583
18 03 2017 15:43:47.331:DEBUG [launcher]: PhantomJS (id 75656583) captured in 1.361 secs
18 03 2017 15:43:47.334:DEBUG [phantomjs.launcher]: 

18 03 2017 15:43:47.336:DEBUG [middleware:karma]: custom files null null null
18 03 2017 15:43:47.336:DEBUG [middleware:karma]: Serving static request /context.html
18 03 2017 15:43:47.337:DEBUG [web-server]: serving: /path/to/app/node_modules/karma/static/context.html
18 03 2017 15:43:47.340:DEBUG [middleware:source-files]: Requesting /base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?916005cc407925f4764668d61d04888d59258f5d /
18 03 2017 15:43:47.340:DEBUG [middleware:source-files]: Fetching /path/to/app/node_modules/jasmine-core/lib/jasmine-core/jasmine.js
18 03 2017 15:43:47.341:DEBUG [web-server]: serving (cached): /path/to/app/node_modules/jasmine-core/lib/jasmine-core/jasmine.js
18 03 2017 15:43:47.342:DEBUG [middleware:source-files]: Requesting /base/bower_components/angular/angular.js?367ccb6484896d3b163b691390f735bfca5cf17e /
18 03 2017 15:43:47.342:DEBUG [middleware:source-files]: Fetching /path/to/app/bower_components/angular/angular.js
18 03 2017 15:43:47.342:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-jasmine/lib/boot.js?945a38bf4e45ad2770eb94868231905a04a0bd3e /
18 03 2017 15:43:47.343:DEBUG [middleware:source-files]: Fetching /path/to/app/node_modules/karma-jasmine/lib/boot.js
18 03 2017 15:43:47.343:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-jasmine/lib/adapter.js?7a813cc290d592e664331c573a1a796192cdd1ad /
18 03 2017 15:43:47.343:DEBUG [middleware:source-files]: Fetching /path/to/app/node_modules/karma-jasmine/lib/adapter.js
18 03 2017 15:43:47.343:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-ng-scenario/lib/angular-scenario.js?df746e558e332348ff12e0f08ddae4697abef3cd /
18 03 2017 15:43:47.343:DEBUG [middleware:source-files]: Fetching /path/to/app/node_modules/karma-ng-scenario/lib/angular-scenario.js
18 03 2017 15:43:47.343:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-ng-scenario/lib/adapter.js?88d12e473235d74e75f0db6cbd01396f5aa58e7b /
18 03 2017 15:43:47.343:DEBUG [middleware:source-files]: Fetching /path/to/app/node_modules/karma-ng-scenario/lib/adapter.js
18 03 2017 15:43:47.344:DEBUG [web-server]: serving (cached): /path/to/app/bower_components/angular/angular.js
18 03 2017 15:43:47.353:DEBUG [web-server]: serving (cached): /path/to/app/node_modules/karma-jasmine/lib/boot.js
18 03 2017 15:43:47.353:DEBUG [web-server]: serving (cached): /path/to/app/node_modules/karma-jasmine/lib/adapter.js
18 03 2017 15:43:47.353:DEBUG [web-server]: serving (cached): /path/to/app/node_modules/karma-ng-scenario/lib/angular-scenario.js
18 03 2017 15:43:47.360:DEBUG [web-server]: serving (cached): /path/to/app/node_modules/karma-ng-scenario/lib/adapter.js
18 03 2017 15:43:47.361:DEBUG [web-server]: serving: /path/to/app/node_modules/karma/static/context.js
18 03 2017 15:43:47.362:DEBUG [middleware:source-files]: Requesting /base/bower_components/angular-mocks/angular-mocks.js?428e663e720ed137f3931dc4e4079d00eb339620 /
18 03 2017 15:43:47.362:DEBUG [middleware:source-files]: Fetching /path/to/app/bower_components/angular-mocks/angular-mocks.js
18 03 2017 15:43:47.364:DEBUG [web-server]: serving (cached): /path/to/app/bower_components/angular-mocks/angular-mocks.js
18 03 2017 15:43:47.440:DEBUG [phantomjs.launcher]: WARNING: Tried to load angular more than once.

18 03 2017 15:43:47.441:DEBUG [phantomjs.launcher]: TypeError: undefined is not a constructor (evaluating 'window.angular.$$csp()')


18 03 2017 15:43:47.441:DEBUG [phantomjs.launcher]:   http://localhost:9876/base/bower_components/angular/angular.js?367ccb6484896d3b163b691390f735bfca5cf17e:33345 in global code

18 03 2017 15:43:47.443:DEBUG [phantomjs.launcher]: TypeError: undefined is not a constructor (evaluating 'angular.module('ngAnimateMock', ['ng'])
  .info({ angularVersion: '1.6.3' })')

  http://localhost:9876/base/bower_components/angular-mocks/angular-mocks.js?428e663e720ed137f3931dc4e4079d00eb339620:800

PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
  TypeError: undefined is not a constructor (evaluating 'window.angular.$$csp()')
  at bower_components/angular/angular.js:33345


18 03 2017 15:43:47.453:DEBUG [karma]: Run complete, exiting.
18 03 2017 15:43:47.454:DEBUG [launcher]: Disconnecting all browsers
PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
  TypeError: undefined is not a constructor (evaluating 'angular.module('ngAnimateMock', ['ng'])
    .info({ angularVersion: '1.6.3' })')
  at bower_components/angular-mocks/angular-mocks.js:800


18 03 2017 15:43:47.456:DEBUG [karma]: Run complete, exiting.
18 03 2017 15:43:47.456:DEBUG [launcher]: Disconnecting all browsers
18 03 2017 15:43:47.471:DEBUG [launcher]: Process PhantomJS exited with code 0
18 03 2017 15:43:47.471:DEBUG [temp-dir]: Cleaning temp dir /var/folders/84/81q1wl5d5k58flxbpcgqq78w0000gn/T/karma-75656583
18 03 2017 15:43:47.478:DEBUG [launcher]: Finished all browsers



via doublesharp

How to make post request to child attribute

How do i make a post request to the product {type: mongoose.Schema.Types.ObjectId, ref: 'Product'} in my schema this is what my schema looks like

const CategorySchema = mongoose.Schema({
name: {
 type: String,
 required: true
},
img_url:{
 type:String,
 required: true
},
product: [
 {type: mongoose.Schema.Types.ObjectId, ref: 'Product'}
 ]
})

but i don't know how i can post to the product array?

router.post('/',(req,res)=>{
    const newCategory = newCategory()
    category.name = req.body.name;
    category.img_url = req.body.img_url;
    Category.save(newCategory,(err,category)=>{
       if (err) {
        console.log(err);
       }else {
        res.json(status: true)
    }
  })
 })



via Paul dolo

What can you do with node.js that you cannot do with a similar technology (or technologies)?

I'm learning the concept of node.js. I'm trying to figure out what can you do only with node.js and not with other technologies.



via mj-programmer

How to get data from the client to the server (without url parameters) in Node.js?

Besides passing data trough the url parameters, how can I get data from, a form in the client index.html to my server.js file in Node.js?

I know how to get the data from the server to the client, but without using url parameters, I don't know how to do it the other way (client to server).



via Diogo Capela

How to generate a list of radio buttons/checkboxes with ejs from JSON object?

I have a json object that I am passing to ejs, and based on certain fields in that object I would like to generate checkboxes and radio buttons, without hardcoding them so they are changed based on the values inside the json object. The number of checkboxes and radio buttons in the lists should expand and contract based on the size of the properties of the json objects. How can I do this?



via daniel metlitski

how to track this in a javascript 6 CLASS (not function) callback in Node.js?

I know there are lots of posts about this in javascript functions and objects, but there seems to be no similar help for javascript classes. classes are different because you cant use the "var self=this" trick to solve the problem. Solutions to not being able to get at class data include:

  1. bind. I have not been able to get this to work through the many levels of indirection required to make the program manageable. I cant find any examples of bind in callbacks without self (which doesnt work in classes) or the underscore library.
  2. arrow functions. these are fine if your entire logic is one line, but all mine are much larger and some need to be called from several places, so these are not an option I assume.
  3. var self = this. As mentioned this does not work in javacript classes.

Here is some code:

class Game{
      constructor(minPlayers) {
         this.minPlayers = minPlayers
         this.players=[]
         this.waitTimer=null
      } // constructor

      addPlayer(player) {
          this.players.plush(player)
          // if we are the first player, set a timeout waiting for others.
          if (this.players.length ==1) {
             this.waitTimer= setTimeout(this.waitForPlayers, 5000)
          } else {
             // stuff
          }
      } // addPlayer

      // this function is too long to be an arrow function.
      waitForPlayers() {
         if (this.players.length < this.minPlayers) { // error this.xx undefined.
              // do stuff
              notifyAllPlayers("Game Aborted, not enough players")  
         } // else ....
      }

      notifyAllPlayers(message){
         for (let i=0; i<this.players.length; i++) {  // error this.players undefined
            console.log(this.players[i].name) // error this.players undefined
         }
      }

} // Game

This is called by something like this:

let Game = require('./game')
let game= new Game(4)
game.addPlayer(bob)

The crux is how to get "this" from a function called by a callback called by a function? Where do all the binds go?



via John Little

bind function in JS without binding 'this' value

Saw we have a simple fn like so:

function run(foo, cb){
   setTimeout(function(){
      cb(null, foo);
   }, 400);
}

and we want to reuse the function, maybe with the async library:

async.map({

foo: run.bind(null,'foo'),
bar: run.bind(null,'bar'),
baz: run.bind(null,'baz')

}, function(err){


});

what I would like to do is avoid binding the "this" value in the function.

One thing we could do is this instead:

   function run(foo){
    return function(cb){
       setTimeout(function(){
          cb(null, foo);
       }, 400);
    }
  }

and then have this:

async.map({

foo: run('foo'),
bar: run('bar'),
baz: run('baz')

}, function(err){


});

this is cleaner, but I think that using the bind functionality can produce more generic code, objectively, over using the latter pattern.

Does anyone know if there is a native way to call bind without binding the "this" value of a function. Or perhaps a way to implement a Function.prototype.bind() function that doesn't bind the "this" value?

Here's my attempt:

Function.prototype.customBind = function(){

    var self = this;
    var args1 = Array.from(arguments);

    return function(){

    var args2 = Array.from(arguments);
    self.apply(this, args1.concat(args2));
   }

};

in this way, we can use the dynamic value for "this"? We would use this code like so:

async.map({

foo: run.bindCustom('foo'),
bar: run.bindCustom('bar'),
baz: run.bindCustom('baz')

}, function(err){


});



via Alexander Mills

Should I migrate to postgres?

I have an application that I rewrite it (server side and client side)

The new server side will be implement in nodejs.

I consider which Database should I choose, (now it's oracle db).

My two options are PostgersSQL or stay with Oracle.

So I have some questions:

  • What prefer to work with nodejs? (oracle/postgres)
  • How much it take to migrate from oracle to postgres?
  • Does any difference in the performance?

Thanks



via user2922456

How do I lock down Firebase Database to any user from a specific (email) domain using the new firebase cloud functions?

Without cloud functions, it appeared that it required a app server to securely limit signups for a firebase app by email domain according to this old question: How do I lock down Firebase Database to any user from a specific (email) domain?

The goal is to allow only signups from a specific domain or set of domains using google authentication and/or other auth providers.

Now that we have firebase cloud functions how can this be accomplished without an app server?



via Mike

the command "npm" returns with an error

*

C:\Users\xxxxx>npm module.js:471 throw err; ^

Error: Cannot find module 'semver' at Function.Module._resolveFilename (module.js:469:15) at Function.Module._load (module.js:417:25) at Module.require (module.js:497:17) at require (internal/module.js:20:19) at Object. >(C:\Users\xxxxx\AppData\Roaming\npm\node_modules\npm\lib\utils\unsupported.js:2:>14) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3)

C:\Users\xxxxx>



via Riyosaki

Babel : turn off import directives transpilation

I am trying to use the babel transpiler to use ES6 in a project, but i'm struggling with something quite unusual : I'm working with an enhanced ES5 js codebase that contains imports and export directives.

Here is an example :

import Widget from 'component:component-widget';

//ES5 code here

export default "something"

I would like to keep those imports, but transpile the rest of detected ES6 features.

I did not find a way to do it so far... :/

Do you know if something like that could be possible?

Thanks in advance!



via gwenp

Websockets and Secure Web Sockets on the same NodeJS server instance

I am developing a home automation system for my home using a nodejs websocket server and several Arduino esp8266 modules as websocket clients. The Arduino libraries I have found do not support secure web sockets so. I was wondering if someone had a solution to implement standard websockets on my local network, but require secure websockets from the wan, all on the same server instance.

Maybe there is a simpler solution that I haven't thought of, but hoping to get a push in the right direction. Thank you!



via Dustin Dwyer

Express.js missing ) after argument list

I have some code:

doc.image('images/pic_1.jpg', 0, 15, scale: 0.25)
    .text('Scale', 0, 0)

Based on official PDFkit documentation: PDFKit documentation But, this didn't work, and node console show me this, error, and underline "scale:0.25" part:

doc.image('images/pic_1.jpg', 0, 15, scale: 0.25) SyntaxError: missing ) after argument list



via Michaell94

Run a JS file in a NodeJS script

I know there are multiple ways of running a script in a NodeJS script. Given that I run start.js, which runs main.js. What I'm looking for is:

  • both scripts run simultaneously
  • console.log and readline input will work in the script that is loaded by the other script (main.js can do console.log and gets console input too)
  • main.js should continue to run when start.js terminates

Based on the last key point, wouldn't I be able to restart a script without an extra package for node, just by launching the same script and then returning?



via Flybel

Alter express routes from one "express capture" to another

In a number of PHP frameworks I've used in the past, there was the ability to match URLs (with or without variables) to a controller / action route.

For example:

/example/:action.:type => /other/:action.:type

This is helpful in some cases.

I was wondering if there was a clean / easy way to do this with express.

It feels like app.use() could be helpful, but the dancing around variables makes me cautious.

Anyone have experience with this?



via Gaunt Face

hapijs yar doesn't work

I am having this in one handler (api/user/login):

 request.yar.set('userSession', {userId: doc.userId});
 console.log(request.yar.get('userSession'));

in second handler I have this (api/user/isLoggedIn):

 console.log(request.yar.get('userSession'));

when I go in browser and do this in console:

$.ajax({
url: 'http://localhost:3004/api/user/login',
method: 'POST',
data: {
    email: 'durisvk2@gmail.com',
    password: 'jjuurr123'
},
success: function(data) {
    console.log(data);
}
})

the server outputs: {userId: 'ASDFGHJKLZX'}

BUT when I do this in Chrome Console:

$.ajax({
url: 'http://localhost:3004/api/user/isLoggedIn',
method: 'GET',
data: {
},
success: function(data) {
    console.log(data);
}
})

I get in console undefined

why isn't it storing session from one request to another?



via durisvk10

Socket.IO only it works locally who can i fixed

I have this Node.JS server:

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


/**
 * Gestion des requêtes HTTP des utilisateurs en leur renvoyant les fichiers du dossier 'public'
 */
app.use('/', express.static(__dirname + '/public'));

/**
 * Liste des utilisateurs connectés
 */
var users = [];

/**
 * Historique des messages
 */
var messages = [];

/**
 * Liste des utilisateurs en train de saisir un message
 */
var typingUsers = [];

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

  /**
   * Utilisateur connecté à la socket
   */
  var loggedUser;

  /**
   * Emission d'un événement "user-login" pour chaque utilisateur connecté
   */
  for (i = 0; i < users.length; i++) {
    socket.emit('user-login', users[i]);
  }

  /**
   * Emission d'un événement "chat-message" pour chaque message de l'historique
   */
  for (i = 0; i < messages.length; i++) {
    if (messages[i].type === 'chat-message') {
      socket.emit('chat-message', messages[i]);
    } else {
      socket.emit('service-message', messages[i]);
    }
  }

  /**
   * Déconnexion d'un utilisateur
   */
  socket.on('disconnect', function () {
    if (loggedUser !== undefined) {
      // Broadcast d'un 'service-message'
      var serviceMessage = {
        text: 'User "' + loggedUser.username + '" disconnected',
        type: 'logout'
      };
      socket.broadcast.emit('service-message', serviceMessage);
      // Suppression de la liste des connectés
      var userIndex = users.indexOf(loggedUser);
      if (userIndex !== -1) {
        users.splice(userIndex, 1);
      }
      // Ajout du message à l'historique
      messages.push(serviceMessage);
      // Emission d'un 'user-logout' contenant le user
      io.emit('user-logout', loggedUser);
      // Si jamais il était en train de saisir un texte, on l'enlève de la liste
      var typingUserIndex = typingUsers.indexOf(loggedUser);
      if (typingUserIndex !== -1) {
        typingUsers.splice(typingUserIndex, 1);
      }
    }
  });

  /**
   * Connexion d'un utilisateur via le formulaire :
   */
  socket.on('user-login', function (user, callback) {
    // Vérification que l'utilisateur n'existe pas
    var userIndex = -1;
    for (i = 0; i < users.length; i++) {
      if (users[i].username === user.username) {
        userIndex = i;
      }
    }
    if (user !== undefined && userIndex === -1) { // S'il est bien nouveau
      // Sauvegarde de l'utilisateur et ajout à la liste des connectés
      loggedUser = user;
      users.push(loggedUser);
      // Envoi et sauvegarde des messages de service
      var userServiceMessage = {
        text: 'You logged in as "' + loggedUser.username + '"',
        type: 'login'
      };
      var broadcastedServiceMessage = {
        text: 'User "' + loggedUser.username + '" logged in',
        type: 'login'
      };
      socket.emit('service-message', userServiceMessage);
      socket.broadcast.emit('service-message', broadcastedServiceMessage);
      messages.push(broadcastedServiceMessage);
      // Emission de 'user-login' et appel du callback
      io.emit('user-login', loggedUser);
      callback(true);
    } else {
      callback(false);
    }
  });

  /**
   * Réception de l'événement 'chat-message' et réémission vers tous les utilisateurs
   */
  socket.on('chat-message', function (message) {
    // On ajoute le username au message et on émet l'événement
    message.username = loggedUser.username;
    // On assigne le type "message" à l'objet
    message.type = 'chat-message';
    io.emit('chat-message', message);
    // Sauvegarde du message
    messages.push(message);
    if (messages.length > 150) {
      messages.splice(0, 1);
    }
  });

  /**
   * Réception de l'événement 'start-typing'
   * L'utilisateur commence à saisir son message
   */
  socket.on('start-typing', function () {
    // Ajout du user à la liste des utilisateurs en cours de saisie
    if (typingUsers.indexOf(loggedUser) === -1) {
      typingUsers.push(loggedUser);
    }
    io.emit('update-typing', typingUsers);
  });

  /**
   * Réception de l'événement 'stop-typing'
   * L'utilisateur a arrêter de saisir son message
   */
  socket.on('stop-typing', function () {
    var typingUserIndex = typingUsers.indexOf(loggedUser);
    if (typingUserIndex !== -1) {
      typingUsers.splice(typingUserIndex, 1);
    }
    io.emit('update-typing', typingUsers);
  });
});

/**
 * Lancement du serveur en écoutant les connexions arrivant sur le port 3000
 */
http.listen(3000); 

client

*global io, rivets, utils*/
/*jslint browser: true*/
var socket = io();
var i, j;

/**
 * Liste des messages
 */
var messages = [];

/**
 * Liste des utilisateurs
 */
var users = [];


/*** DataBinding initial ***/

rivets.bind($('#messages'), { messages : messages });
rivets.bind($('#users'), { users : users });


/*** Gestion des événements ***/

/**
 * Connexion de l'utilisateur
 * Uniquement si le username n'est pas vide et n'existe pas encore
 */
$('#login form').submit(function (e) {
  e.preventDefault();
  var user = {
    username : $('#login input').val().trim()
  };
  if (user.username.length > 0) { // Si le champ de connexion n'est pas vide
    socket.emit('user-login', user, function (success) {
      if (success) {
        $('body').removeAttr('id'); // Cache formulaire de connexion
        $('#chat input').focus(); // Focus sur le champ du message
      }
    });
  }
});

/**
 * Envoi d'un message
 */
$('#chat form').submit(function (e) {
  e.preventDefault();
  var message = {
    text : $('#m').val()
  };
  $('#m').val('');
  if (message.text.trim().length !== 0) { // Gestion message vide
    socket.emit('chat-message', message);
  }
  $('#chat input').focus(); // Focus sur le champ du message
});

/**
 * Réception d'un message
 */
socket.on('chat-message', function (message) {
  message.label = message.username;
  messages.push(message);
  utils.scrollToBottom();
});

/**
 * Réception d'un message de service
 */
socket.on('service-message', function (message) {
  message.label = 'information';
  messages.push(message);
  utils.scrollToBottom();
});

/**
 * Connexion d'un nouvel utilisateur
 */
socket.on('user-login', function (user) {
  users.push(user);
  setTimeout(function () {
    $('#users li.new').removeClass('new');
  }, 1000);
});

/**
 * Déconnexion d'un utilisateur
 */
socket.on('user-logout', function (user) {
  var userIndex = users.indexOf(user);
  if (userIndex !== -1) {
    users.splice(userIndex, 1);
  }
});

/**
 * Détection saisie utilisateur
 */
var typingTimer;
var isTyping = false;

$('#m').keypress(function () {
  clearTimeout(typingTimer);
  if (!isTyping) {
    socket.emit('start-typing');
    isTyping = true;
  }
});

$('#m').keyup(function () {
  clearTimeout(typingTimer);
  typingTimer = setTimeout(function () {
    if (isTyping) {
      socket.emit('stop-typing');
      isTyping = false;
    }
  }, 500);
});

/**
 * Gestion saisie des autres utilisateurs
 */
socket.on('update-typing', function (typingUsers) {
  for (i = 0; i < users.length; i++) {
    users[i].typing = false;
  }
  for (i = 0; i < typingUsers.length; i++) {
    for (j = 0; j < users.length; j++) {
      if (typingUsers[i].username === users[j].username) {
        users[j].typing = true;
        break;
      }
    }
  }
});

https://github.com/BenjaminBini/socket.io-chat.git i like to connect to computer but The problem is that it seems to be only working locally. Any idea on what the problem might be?



via Mohamed Zaouali

How do I run Meteor using NodeJS v6 LTS (or a specific NodeJS version)?

I understand that Meteor comes with NodeJS bundled as a dependency, but I have a module written in ES6 with a default argument value declared in one of the Class methods. It's currently erroring using Meteor v1.4.3.2 like so:

(STDERR) packages/modules.js:374
(STDERR)   constructor(options={format:'.json'}) {
(STDERR)                      ^
(STDERR)
(STDERR) SyntaxError: Unexpected token =

Do I need to rewrite the module to NOT use the default argument? Or is there a way to force Meteor to run v6? OR... is there a fork of a development version of Meteor that I may use for my project?



via toszter

Can't see my html file in view

I am trying to run basic mean app. My app is working without the angular part. But when I have included angular I can't see the html page which is in the "view" folder.

This is my server:

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

var index=require('./routes/index');
var tasks=require('./routes/tasks');
var port=3000;
var app=express();

/*View engine*/
app.set('views',path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.engine('html',require('ejs').renderFile);

/*View static folder*/
app.use(express.static(path.join(__dirname, 'client')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use('/',index);
app.use('/api',tasks);
app.listen(port, function(){
    console.log('The application is running on port '+port);
});

This is my route to index under "routes" directory:

var express=require('express');
var router=express.Router();

router.get('/',function(req, res, next){
    res.render('index.html');
})
module.exports=router;

My angular code is living in client/app directory. I am typing "npm start" when I am in myapp/client directory in the terminal. I get "Can't get/" and in the terminal I see "404 GET /index.html"

Any ideas? Thanks!



via Tuvia Khusid

Not receiving notifications when app is killed FCM functions

Firebase currently rolled out Firebase Functions to add server side code.

I am currently using this approach for notifications on receiving a message from a sender.

Everything seems fine but when i kill the app I dont receive notifications.

I saw some answers regarding it that i should use just data message and receive in onMessageReceived() but its not working for killed app. What should i do?

NodeJS Index.js

exports.sendNewMessageNotification = functions.database.ref('/rootssahaj/authGplus/users/{userTorS}/{userTeacherUID}/messages/{chatWithOthUser}/{messageUID}').onWrite(event => {
console.log('called1 ');
const TeacherUid = event.params.userTeacherUID;
const whoTorS=event.params.userTorS;
var whoOppTorS=null;
if (whoTorS=="teachers") {
    whoOppTorS="students";
}else{
    whoOppTorS="teachers";
}
var StudentUid = event.params.chatWithOthUser;
StudentUid=StudentUid.substring(8);

console.log('called2 ')

if (!event.data.val()) {
return console.log('No Change ');
}

console.log('Event data: ',StudentUid, event.data.val());
if (StudentUid!=event.data.val().sender) {
return console.log('Different sender ',event.data.val().sender);
}

// Get the list of device notification tokens.
const getDeviceTokensPromise = admin.database().ref(`/rootssahaj/authGplus/users/${whoTorS}/${TeacherUid}/profile/fcmtoken`).once('value');

// Get the follower profile.
const getFollowerProfilePromise = admin.database().ref(`/rootssahaj/authGplus/users/${whoOppTorS}/${StudentUid}/profile`).once('value');

return Promise.all([getDeviceTokensPromise, getFollowerProfilePromise]).then(results => {
const tokensSnapshot = results[0];
const follower = results[1];
console.log('Token: ', tokensSnapshot.val(),' ',follower.val());
// Check if there are any device tokens.
if (tokensSnapshot.val()==null) {
  return console.log('There are no notification tokens to send to.');
}
console.log('There are', tokensSnapshot.numChildren(), tokensSnapshot,'tokens to send notifications to.');
console.log('Fetched follower profile', follower.val().userNAME);

// Notification details.
const payload = {
  data: {
    body: `new message: ${event.data.val().text}`,
    title: `${follower.val().userNAME}`,
  }
};
var options = {
priority: "high"
};

// Listing all tokens.
//const tokens = Object.keys(tokensSnapshot.val());
// console.log('tokens', tokens);

// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokensSnapshot.val(), payload,options).then(response => {
  // For each message check if there was an error.
  const tokensToRemove = [];
  response.results.forEach((result, index) => {
    const error = result.error;
    if (error) {
      console.error('Failure sending notification to', tokens[index], error);
      // Cleanup the tokens who are not registered anymore.
      if (error.code === 'messaging/invalid-registration-token' ||
          error.code === 'messaging/registration-token-not-registered') {
        //tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
      }
    }
  });
  return Promise.all(tokensToRemove);
});
});
});



via Sahaj Rana

Getting a TypeError: * is not a function error

I'm getting the following error in my server.js:

TypeError: routing is not a function

on

routing(app);

routing.js:

// JavaScript source code
var friends = require('./../controllers/friends.js');

module.export = function(app)
{...}



via JSim

Web applications with javascript

Now I program all my web apps with Flask or Django. (blogs, social networks...). I need templates, db access, controllers, routing...

Now I want to do same web applications, but with javascript.

People tell me : You need NodeJs for server-side, Angular for the front, and for example firebase or mongodb. Or also you can use Express JS.

But can I just use Angular JS and Firebase for start a big web app ? Need I Node if Angular can Access/Update/Delete in my db ?



via Alexandre

npm install --save-dev gulp

I am trying to learn node and npm and gulp and all but am running into this error.

$ npm install --save-dev gulp
npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "--save-dev" "gulp"
npm ERR! node v6.10.0
npm ERR! npm  v3.10.10
npm ERR! code SELF_SIGNED_CERT_IN_CHAIN

npm ERR! self signed certificate in certificate chain
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\davidb\desktop\testproject\npm-debug.log

Does anyone know how to fix this? I am using gitbash instead of node because in my node i cannot even do node-v I have to use process.version to even get the version. And help with this would be greatly appreciated! I have been using http://blog.npmjs.org/post/78165272245/more-help-with-selfsignedcertinchain-and-npm to try to fix the issue but nothing is working.



via David Brierton

returned promise is undefined in nodejs

I have a function in some model file:

  module.exports.getGroupsOtherThanSelectedGroupAndItsDescendents = wrap(function*(topGroupId, generations) {

  const topGroup = yield Group.find({parent: topGroupId}).populate('parent').populate('effect').populate('nature');

  let groups = [];
  let ids = [topGroupId];

  for(let i = 0; i < generations; i++) {
    const thisLevelGroups = yield Group.find({ parent : { $in : ids } }).populate('parent').populate('effect').populate('nature');
    ids = thisLevelGroups.map(group => group._id);
    groups = groups.concat(thisLevelGroups);
  }

  Group.getAllGroups(function(err, allGroups) {

    groups.forEach(function(group) {
        var index = allGroups.map(function(thisGroup) { return thisGroup.name; }).indexOf(group.name);
        allGroups.splice(index, 1);
    }, this);

    return allGroups;

  });

});

Now I am calling this function as follows from another file:

Group.getGroupsOtherThanSelectedGroupAndItsDescendents(groupId, 100).then(function(selectedGroups) {

    console.log(selectedGroups);
});

But always, I get selectedGroups as undefined.

I think the problem is :

Before allGroups is returned from async method called getAllGroups, the value of selectedGroups is returned. so it is undefined.

But I don't know how to solve this problem.



via Vishal

handle live data from RESTful API

I am trying to call an RESTful API to get the necessary data using node.js. They said that they update the data as it changes automatically, but how can they continuously update the data when it is just being called through a GET request? Also how would I receive the data using node.js for this.



via dgelinas21

Failed to load angular2-onsenui

did

npm install angular2-onsenui@latest.
npm install onsenui@2.2.x.

followed by the change in systemjs.config.js to map to angular2-onsenui.umd.js Here is my full systemjs.config.js

/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
      'angular2-onseni': 'npm:angular2-onseni/dist/bundles/angular2-onsenui.umd.js'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);

Tried this, didn't help.

In package.json installed vesrsions are:

"angular2-onsenui": "^1.0.0-rc.6",
"onsenui": "^2.2.0"

The error message in browser(chrome)

http://localhost:3000/angular2-onsenui Failed to load resource: the server responded with a status of 404 (Not Found)



via ishandutta2007

NodeJS and C# app EBUSY error

I am currently developing an nodeJS app. I use a simple C# program to create a text file. That file is like a token which helps me to continue the execution of nodeJS app.I have the following javascript code:

function take_tool() {
    while(take_tool_flag == false) {
        if(fs.existsSync('D:/flag.txt')) {
            fs.writeFileSync('D:/input_robot.txt', '-1');
            console.log('Robot is taking the tool!');
            fs.unlinkSync('D:/flag.txt');
            take_tool_flag = true;
        }
    }
}

function draw_table() {
    while(draw_table_flag == false && take_tool_flag == true) {
        if(fs.existsSync('D:/flag.txt')) {
            fs.writeFileSync('D:/input_robot.txt', '-3');
            console.log('Robot is drawing the table game!');
            fs.unlinkSync('D:/flag.txt');
            draw_table_flag = true;
        }
    }
}


function game() {

    console.log("Game has started!");

    fs.writeFileSync('D:/input_robot.txt', '-99');

    take_tool();

    draw_table();
}

game();

And this is the code for C# program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i <= 10; i++)
            {
                System.Threading.Thread.Sleep(10000);
                Console.WriteLine("File created!");
                File.Create(@"D:\flag.txt", 1024);
            }
        }
    }
}

I run the nodeJS app with "node filename.js" and then it wait for flag.txt to be created. But when i run C# program i get the following error:

enter image description here

Any ideas? Node version: 6.9.2.



via Codrut Tapu

Parse codeigniter's session data from redis

I made a simple login functionality that stores the following array into the session:

$sessionData=[
              'username'=>/*username of the loged in user*/,
              'user_id'=>/*user id of the logedin user*/
             ];

And I wanted the authorized user to be able to be able to chat into the following chat page that gets served via Codeigniter:

 <?php 
$this->load->helper('url');
?>
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Messaging</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="<?=base_url('assets/css/bootstrap/bootstrap.min.css');?>" rel="stylesheet"  >

    <script src="<?=base_url('assets/js/jquery.min.js')?>"></script>
    <script src="<?=base_url('assets/js/bootstrap.min.js')?>"></script>
    <script src="<?=base_url('assets/js/socket.io.min.js')?>"></script>
    <script>
        $(function () {
            var socket = io('http://localhost:3000');
            $('form').submit(function(e){
                e.preventDefault();
                socket.emit('chat message', $('#m').val());
                $('#m').val('');
            });

            socket.on('chat message', function(msg){
                    $('#messages').append($('<div class="col-xs-12">').text(msg));
            });
        });
    </script>
</head>
<body>
    <div id="messages" style="max-height:100%" class="container-fluid">

    </div>
    <div class="container-fluid">
        <div class="col-xs-12">     
            <form action="" class="form-inline bg-success">
                <div class="form-group">
                 <input id="m" type="text" class="form-control" autocomplete="off" />
                </div>
                <button class="btn btn-primary">Send</button>
            </form>
        </div>
    </div>
</body>

As you can see it uses socker.io on a node.js server listening into port 3000. But I want to put some authentication into the socket.io server in order not to be able for 3rd party applications with unauthorized users to use it.

As I noticed as long as the websocket uses the same domain the codeigniter';s cookie gets passed on the node.js' socket.io. So I thought that I needed a middleware in order to get coceigniters session data from redis.

So in the first place I wanted to have a look on how the data gets stored on redis server so I connected via redis-cli --scan --pattern '*' command and I got the following results:

ci_session:uipchhk7lfc5vmodndljquqsbs2ru02d
ci_session:gvmio1esujbscbh8847olbn4hkg5897n
ci_session:iejok3chmv025keh5g52lj3lps701umj

But they do not seem in any usefull form. So I wanted to know:

What are these data above? How I will get the session information I want from the node.js application?



via Dimitrios Desyllas

How can i decode unicode string in javascript

I have a string like \uC88B\uC544\uC694.
In a node repl(v7.4.0), this statement shows '좋아요' correctly. but in below code, it's not working.

var request = require('request');

request.post(
  {
    url: 'http://book.daum.net/dwr/call/plaincall/ajaxDetailController.getReviewListByPageNo.dwr',
    form: {
      callCount: 1,
      'c0-id': 0,
      'c0-scriptName': 'ajaxDetailController',
      'c0-methodName': 'getReviewListByPageNo',
      'scriptSessionId': '${scriptSessionId}714',
      'batchId': 6,
      'c0-param0': 'Object_Object:{bookid: KOR9791186757093, pageNo: 1, pageSize: 6}'
  }
}, 
(error, response, body) => {
  var str = 's2';
  var regex = new RegExp(str + `.\\w*\\=[\\"\\w\\d\\s\\\\\\&\\:\\/\\.]*\\;`, 'g');
  const arr= body.match(regex);
  /* HERE */
  console.log(arr[14].split('"')[1]);
  console.log(arr[25].split('"')[1]);
  console.log(arr[41].split('"')[1]);
  console.log(arr[35].split('"')[1]);
  console.log(arr[44].split('"')[1]);
  console.log(arr[13].split('"')[1]);
}
);

Why it doesn't show the correct string?



via dali high

Node JS or PHP callback after some time

I have writing taxi service app, and have a question about architecture / technology.

  • client app make a request for car;
  • its waiting some time (3 min);
  • if nobody accept this order request, passenger receive push notification "driver not found"

I am asking about how to make this wait function.

Which is better node js OR php (server already written on php but i can make this call on node).

Which framework need to use for this(if its needed).

And which CPU load will be?

Thanks!



via Vadim Kozak

Get attribute from button to node using ajax

I'm simply trying to get the name of a clicked button to my node server and am stuck on something small. If I have something like this in node:

app.get('/someurl', function(req, res) {

    console.log(req.body.name);

});

And my jQuery/ajax looks something like this:

$(document).ready(function() {
  $('button').click(function() {
    buttonName(this.name);
  });
});

function buttonName(name) {
  $.ajax({
  type: 'get',
  url: '/someUrl',
  dataType: 'json',
  data: {'name' : name }
 })
}

What am I doing wrong? I'm using body-parser in node and have -

app.use(bodyParser.urlencoded({ extended: false }));



via Ja5onHoffman

Firebase firebase-web.js missing

I installed angular firebase using node.js however the firebase-web.js file is missing. I have searched for this file and cannot find it. Does anyone know a solution?



via Aueisbiejei3i939

Socket.io on Google Cloud Platform

I am trying to deploy a node.js app to Google Cloud Platform. It includes the following parts:

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

serv.listen(65080);

var io = require('socket.io')(serv, {});

I am able to deploy it, but the link is giving an error. You can check it here.

I also checked out this link, but I couldn't fix my problem. I opened the firewall, but I'm still getting an error.

Any help is greatly appreciated. Thanks in advance.



via user3279394

docker nodejs container cant connect mysql container

I'm running Docker server in Digital Ocean. There I have two containers Nodejs and Mysql. Mysql container has open port to 3306.

When trying to access mysql via nodejs by Docker Server ip + port. I get Error: connect ETIMEDOUT.

When I run same nodejs docker setup in my local computer it works fine. Is there something i'm missing?



via user257980

complex iteration logic in hogan js?

I'm trying to learn expressjs, I have a controller which queries a db, and returns a JSON object which looks something like this:

[ { _id: 58cb851721c1c107ab436686,                                                                                                                             
   title: 'some title',                                                                                                                        
   content: 'this is content' },                                                                                                           
  { _id: 58cb856321c1c107ab436688,                                                                                                                             
   title: 'ah yes',                                                                                                                                           
   content: 'more title and contents' } 
   ...
   ...
]

What I now want to do is display every element in the array in a MDL card layout. So, If the above json object has 20 objects, there should be 20 cards each showing values of their respective _id, title and content properties. To do that I'll have to use a for loop somewhat like this:

for(var i = 0; i < data.length; i++) {
    <span>  </span> </br>
    <span>  </span> </br>
    <span>  </span> </br>
  }

This is clearly very easy with something like ejs because it allows loop logic inside the templates. But I have no clue how to do that in HoganJS's lack of a proper documentation clearly isn't helping. I've searched a lot on the interwebs with no avail. Currently I'm rendering the template like:

res.render('index');

Is it possible to do this in hogan, how? or I'll need to do some gymnastics in my routes?



via Edward McKinzie

How do I upload a base64 encoded image (string) directly to a Google Cloud Storage bucket using Node.js?

Currently, I am using the @google-cloud/storage NPM package to upload a file directly to a Google Cloud Storage bucket. This requires some trickery as I only have the image's base64 encoded string. I have to:

  • Decode the string
  • Save it as a file
  • Send the file path to the below script to upload to Google Cloud Storage
  • Delete the local file

I'd like to avoid storing the file in the filesystem altogether since I am using Google App Engine and I don't want to overload the filesystem / leave junk files there if the delete operation doesn't work for whatever reason. This is what my upload script looks like right now:

// Convert the base64 string back to an image to upload into the Google Cloud Storage bucket
var base64Img = require('base64-img');
var filePath = base64Img.imgSync(req.body.base64Image, 'user-uploads', 'image-name');

// Instantiate the GCP Storage instance
var gcs = require('@google-cloud/storage')(),
    bucket = gcs.bucket('google-cloud-storage-bucket-name');

// Upload the image to the bucket
bucket.upload(__dirname.slice(0, -15) + filePath, {
    destination: 'profile-images/576dba00c1346abe12fb502a-original.jpg',
    public: true,
    validation: 'md5'
}, function(error, file) {

    if (error) {
        sails.log.error(error);
    }

    return res.ok('Image uploaded');
});

Is there anyway to directly upload the base64 encoded string of the image instead of having to convert it to a file and then upload using the path?



via Nag

Receive a file with commands as parameter in Nodejs

I have a question maybe i'll find some answers from you .

Well , i want to write an interpreter that receives a file with commands as parameter in nodejs

For example :

node test.js robot.s

robot.s contains :

# Move
FORWARD 100
COMMAND_WITH_ERROR 
BACKWARD 6

Any ideas how i can start ?

Thank you



via infocrasher

socket.io and vue.js fetching data

I am trying to fetching the data of vue.js using this

fetchData: function () {
                socket.emit('getAllSongs')
                socket.on('allSongs',function(data) {
                    this.songs = data
                });

          }

FetchData is called when the vue app is created

created: function () {
            this.fetchData();
        }

But when I try to call the variable songs outside socket.on it stills empty.

What could I do?



via Rafael Andrade

Using Nodemon with BrowserSync on Gulp

I have gulpfile.js like below in normal HTML project. Now, I'm creating a Node/Express project on another project and I want to use Nodemon/Browsersync sametime on Gulp.

By the way I've tried some other samples before submitting this question but I haven't been successfull.

So, how should I set my gulpfile.js for using Nodemon/Browsersync on Gulp?

var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var plumber = require('gulp-plumber');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var cleanCSS = require('gulp-clean-css');
var rename = require("gulp-rename");
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
var browserSync = require('browser-sync').create();
var sourcemaps  = require("gulp-sourcemaps");

// Error Handling
var gulp_src = gulp.src;
gulp.src = function() {
  return gulp_src.apply(gulp, arguments)
    .pipe(plumber(function(error) {
      // Output an error message
      gutil.log(gutil.colors.red('Error (' + error.plugin + '): ' + error.message));
      // emit the end event, to properly end the task
      this.emit('end');
    })
  );
};

// Styles
gulp.task('styles', function() {
  return gulp.src('./src/sass/*.scss')
  .pipe(sass())
  .pipe(autoprefixer('last 2 versions'))
  .pipe(sourcemaps.init())
  .pipe(gulp.dest('./dist/css/'))
  .pipe(cleanCSS())
  .pipe(sourcemaps.write())
  .pipe(concat("main.css", {newLine: ""}))
  .pipe(gulp.dest('./dist/css/'))
  .pipe(browserSync.reload({ stream: true }))
});

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

// BrowserSync
gulp.task('browserSync', function() {
  browserSync.init({
    server: {
      baseDir: './'
    },
    open: false,
    // browser: "Google Chrome",
    notify: false,
    // notify: {
    //     styles: {
    //         top: 'auto',
    //         bottom: '0'
    //     }
    // },
    snippetOptions: {
      rule: {
        match: /<\/body>/i,
        fn: function (snippet, match) {
          return snippet + match;
        }
      }
    }
  })
})

// Watch task
gulp.task('watch', ['browserSync'], function() {
  gulp.watch('./src/sass/*.scss', ['styles']);
  gulp.watch('./*.html', browserSync.reload);
  gulp.watch('./src/js/*.js', ['scripts']);
});

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



via fatihturan

hapijs handlebars not responding

I am trying to use a handlebars but the page is not responding when my routes are correct.

I have this in my server.js, I am not showing it all, only the important parts:

const Hapi = require('hapi');
const Good = require('good');
const Vision = require('vision');
const routes = require('./src/routes');

const server = new Hapi.Server({
connections: {
    routes: {
        files: {
            relativeTo: Path.join(__dirname, 'public')
        }
    }
}
});

server.register([{
    register: Good,
    options: {
    ...
}, {
    register: Vision,
}
], (err) => {


server.views({
    engines: {
        'html': {
            module: require('handlebars'),
        }
    },
    relativeTo: __dirname,
    path: 'templates',
});

routes(server);

server.start((err) => { ...

});

In my routes.js I have this (again only the important parts):

server.route({
    method: 'GET',
    path: '/demo',
    handler: (request, reply) => {
        reply.view('index.html');
    }
});

I get no response from the server, when I do localhost:3004/demo. The file index.html EXISTS! I am sure about that. The Chrome keeps loading and loading forever. What could be the problem? Is there any way to debug this? I get no errors. I've tried a lot of things like providing the full path instead of relativeTo and path.

What am I missing?



via durisvk10

node.js ~ express req.on()

This is an Express middleware thing.

I can't understand how to trigger the req.on() in the following. I've read numerous documents and forum question-answers.

Please explain to me what causes the req.on('data', f()) callback to fire?

I'm seeing the first console.log() but not the inner/second one.

From app.js:

app.use('/api/order', function (req, res, next) {
    console.log("req on(data)");
    req.rawBody = '';
    req.on('data', function (chunk) {
        req.rawBody += chunk;
        console.log("chunk", chunk);
    });

    next();
});



via user2367083

JSON - Wait for loop to finish and then pass data to callback

I'm having a serious issue with Node.js
I'm developing an API to get back data from Facebook Databases using GraphQL and then send back JSON with selected data.

The issue comes when I iterates (with a for loop) through the response array to select the useful data, I don't know how to get all the data and then send it to client. I thought that calling the callback at each iteration would be nice but it didn't solve the problem

Here is the code from my API

Read data from GraphQL
FB.api('me/feed', ...) returns an array of all the data.
The second call returns individual post details, this is the most important part (I have to return an array of this details to the client in json format)

module.exports = function (start, end, callback) {
  if (start > end) throw 'Start is greater than end';

  FB.api('me/feed', function (res) {
    // Error handling
    if (!res || res.error) {
      throw 'FB error occurred: ' + res.error;
    }
    console.log('FB: OK');

    for (let i = start; i < res.data.length && i != end; i++) {
      FB.api(res.data[i].id + '/attachments', function(post) {
        callback({
          id: res.data[i].id,
          type: post.data[0].type,
          postDesc: res.data[i].message.split('\n\n')[0],
          postUrl: post.data[0].url,
          imagePreviewUrl: post.data[0].media.image.src
        });
      });
    }
 });
}



via Andrea Busà

Combine static site with node and add some AJAX

A bit new to the JS and Node landscape. I would like to ask you few questions. I had a simple site, with a structure imagine like:

mysite
  --index.html
  views
    --list.html
    --add.html

Now I wanted to serve my site from Node. All I did was restructure it in this way:

mysite
  index.js
  public
     --index.html
     views
       --list.html
       --add.html

In index.js added ability to serve static pages:

var app = express();
app.use(express.static(__dirname + "/public"));

Finally, now also say from list.html I want to issue an AJAX to my node server, for that I have (inside script):

$.get("/listofmovies", function(data, status){});

and on node:

app.get("/listofmovies", function(request, response){});

This all seems to work, my only question is:

is this the right way (or one of right ways) to set up a web site like this? and run it on node server?



via Giorgi Moniava

Return callback from procedure in node oracledb

I have a procedure which returns a cursor as one of its OUT variables. I am using node oracledb to get the result. Taking the help from the node oracledb documentation, I was able to execute the procedure. Now, I want to return callback from procedure so that I can use it in multiple files without having to write the entire code again just like this.

The code I have written is as follows -

var oracledb = require('oracledb');
var dbConfig = require('./config.js');

var numRows = 10;  // number of rows to return from each call to getRows()
oracledb.outFormat = oracledb.OBJECT;
oracledb.getConnection(
  {
    user          : dbConfig.user,
    password      : dbConfig.password,
    connectString : dbConfig.connectString,
    myProc : dbConfig.proc1
  },
  function(err, connection)
  {
    if (err) { console.error(err.message); return; }
    var bindvars = {
      cursor:  { type: oracledb.CURSOR, dir : oracledb.BIND_OUT },
      error_code : { type: oracledb.STRING, dir: oracledb.BIND_OUT },
      error_msg : { type: oracledb.STRING, dir: oracledb.BIND_OUT }
    };
    connection.execute(
      "BEGIN gt_log(:cursor,:e_cde,:e_msg); END;",
      bindvars,
      function(err, result)
      {
        if (err) {
          console.error(err.message);
          doRelease(connection);
          return;
        }
        console.log(result.outBinds.cursor.metaData);
        fetchRowsFromRS(connection, result.outBinds.cursor, numRows);
      });
  });

function fetchRowsFromRS(connection, resultSet, numRows)
{
  resultSet.getRows( // get numRows rows
    numRows,
    function (err, rows)
    {
      if (err) {
        console.log(err);
        doClose(connection, resultSet); // always close the result set
      } else if (rows.length === 0) {    // no rows, or no more rows
        doClose(connection, resultSet); // always close the result set
      } else if (rows.length > 0) {
        console.log("fetchRowsFromRS(): Got " + rows.length + " rows");
        console.log(rows);
        fetchRowsFromRS(connection, resultSet, numRows);
      }
    });
}

function doRelease(connection)
{
  connection.close(
    function(err)
    {
      if (err) { console.error(err.message); }
    });
}

function doClose(connection, resultSet)
{
  resultSet.close(
    function(err)
    {
      if (err) { console.error(err.message); }
      doRelease(connection);
    });
}

Can anyone help me in converting this to something like this? So that I just have to call a function.



via Dalton2

Data limit on server caching?

I am looking to implement a caching layer to avoid running up costs of API calls, however I would need to cache a significant amount of data. Is there typically a limit on the amount of data you should have cached for good practice? I am pretty new to the use of cache layers, so any advice is appreciated.



via dgelinas21

Node JS sort array passed with Handlebars template client side

I'm developing a simple web app, using nodeJS, express, MongoDB and Handlebars. Server side I use express-handlebars:

var exphbs = require('express-handlebars');
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs(
    {
        defaultLayout:'layout',
        helpers: { /*my helpers*/}}));

So, when I query the db I want to show the result to the client in a page: /* some code */ router.get('/', function(req, res) {

    /*query to mongo DB with mongoose*/
    Coll.find(queryParams, function(err,coll){
        if(err) {
                    console.log(err);
                    throw err;
                }
                else {
                    res.render('index', {'coll': coll});
                }
    });

Showing the result is quite simple with handlebars:





But I would like to allow the user to sort this array of elements without interact again with the server, given that the query results would be the same and will change only the order. the html code would be:

<select id=id>
<option>sort1</option>
<option>sort2</option>
</select>



<script>
$(document).ready(function () {
    $('#id').change(function(){

//DO SOME STUFF WITH LIST
});
</script>

Does it exist a method to sort client-side the array passed via res.render(...) ? If the user choose an option in a select tag, can I use AJAX to modify the list? And how? (always without interact with the server and without execute again the same query on mongoDB)

PS: I'm a beginner with nodeJS and Handlebars, please be patient!



via Giacomo Resci

Unable to return _id of a subdocument using mongoosejs

[
{
    "_id": "58b89de6a480ce48c8f3742d",
    "name": "Core Site",
    "version": "1.0.0",
    "author": "Jane Doe",
    "vendor": "Online Banking",
    "steps": [
        {
            "name": "Step 1: Fun Stuff",
            "dependencies": "1,2,3,4",
            "resource": "TS",
            "weight": 0
        },
        {
            "name": "Step 2: Weird Stuff",
            "dependencies": "3,4",
            "resource": "PS",
            "weight": 1
        }
    ]
},
{
    "_id": "58b8a22097fbe41746827ac7",
    "name": "Online Statements",
    "version": "1.0.0",
    "author": "John Doe",
    "vendor": "Online Banking",
    "steps": [
        {
            "name": "Step 1: Fun Stuff",
            "dependencies": "1,2,3,4",
            "resource": "TS",
            "weight": 0
        }
    ]
}]

I have saved this information into a MongoDB but when I try to get this information the sub-document "Steps" does not include the _id that I can see using Robomongo.

My schema is as follows:

    // grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var stepSchema = new Schema({
  name: { type: String, required: true},
  dependencies: String,
  resource: String,
  weight: Number
})

// create a schema
var sopSchema = new Schema({
  name: { type: String, required: true, unique: true },
  version: String,
  author: String,
  vendor: String,
  steps: [stepSchema]
});



// the schema is useless so far
// we need to create a model using it
var Sop = mongoose.model('Sop', sopSchema);

// make this available to our users in our Node applications
module.exports = Sop;

My end goal is to check if the step is already included and update it when making a change on the front end. So i wanted to get this reference to ensure i have the right subdocument.

My get statement is as follows in my nodejs server.

router.route('/sops')
    .get(function(req, res) {
        Sop.find(function(err, sops) {
            if (err)
                res.send(err);

                var subdoc = sops[0].steps[0];
                console.log(subdoc);
            res.json(sops);
    });
})



via Ben Gummelt

yarn does not work on aws linux

I have successfully installed yarn package manager for my node.js project. It works fine for mlocal host, but when I am checking out the same code repository on aws linux machine and then when I start hitting the APIs , they don't work. But If i remove yarn then it starts working.

These are the following steps that I am doing on aws for that:

1) sudo git clone ..... 2) sudo npm install -g yarn 3) yarn install 4) node app.js

Thw aws configuration are as follows:

t1.micro instance, ubuntu 14.04



via M thaker

In node-js: app.render('filename') generating error on chrome of internal server error.

I'm trying to render the profile.ejs page, but it show the error of "Internal server error".

Status Code:500 Internal Server Error.

var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.get('/',function(req, res){
  res.sendFile(__dirname + '/index.html');
});
app.get('/profile/:id',function(req, res){
  res.render('profile');
});
app.listen(3000);



via ProgSMI

Firebase function not getting called

I have a likes value in the database and i want to change the value STATE when likes is more than 10. Here is my database structure

enter image description here

My firebase function

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.newPost = functions.database
.ref('/QUESTIONS/SPANISH/{postID}'/"LIKES")
.onWrite(function(event) {

 const likes=event.data.value;
 const id=event.params.postID;

 if(likes>10){

    return event.data.ref.parent.child('STATE').set("ACEPTED");
 }
 return false;

});

The function is deployed correctly and all but when i increment the likes nothing happens, what i am doing wrong?



via Tinco De Simone

nginx TCP request failed with status 400

14.195.188.230 - - [18/Mar/2017:16:43:11 +0000] "(004026579154BP05000004026579154111213V0000.0000N00000.0000E000.0000000000.0010000000L0000021C)" 400 173 "-" "-" "-"

This is the log that i can see in my nginx access log, I need this data in my node server.

(004026579154BP05000004026579154111213V0000.0000N00000.0000E000.0000000000.0010000000L0000021C)

1) I am using elastic Beanstalk, i don't know how can i pass the above value to my node server module? If its possible to get that value as http or https request inside my node express module.

2) If i have to run a net server, than in which port should i listen for tcp, and how nginx will know about that port, for http server port, i use process.env.port



via bikash

[SOLVED]Implicit async custom validators (custom validators that take 2 arguments) are deprecated in mongoose >= 4.9.0

I'm using mongoose 4.9.0. Whilst the code below works, I get a warning like the following:
(node:24769) DeprecationWarning: Implicit async custom validators (custom validators that take 2 arguments) are deprecated in mongoose >= 4.9.0. See http://mongoosejs.com/docs/validation.html#async-custom-validators for more info.
I suspect the error is coming from the model validators.
const mongoose = require('mongoose');
const isEmail = require('validator/lib/isEmail');

const Schema = mongoose.Schema;

const userSchema = new Schema({
  email: {
    type: String,
    unique: true,
    required: true,
    validate: [{ validator: isEmail, msg: 'Invalid email.' }],
  },
});

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

The only custom validator I seem to have is isEmail from the validator library, which given an string value returns whether it is valid or not.


via zurfyx

how does it.each work in mocha?

I am trying to understand how it.each function work in mocha.js I have the following code :

describe('fetch all the selected topics',function(){
        it.each([1,2,3,4], 'should loop over each element in an array', function(count){
            fetchSelectedTopics(driver,count); // function that does something
        });

    }); 

        describe('Coach Sign In',function(){
            it('log in as coach',function(done){
                driver.get('https://dev.pluma.co/coach-sign-in');
                done();
            });
            it('login as coach',function(done){
                login.username(coach,driver);
                login.password(coachPassword,driver);
                driver.findElement(webdriver.By.className("client-onboarding-signin-btn")).click().then(function() {
                    done();
                });
            });
        });

Now ideally i am expecting the fetchSelectedTopics to run 4 times and then run the next set of describes. But it doesn't work that way, I want to make the process asynchronous currently instead of running the fetchSelectedTopics 4 times it calls coach sign in url and coach login. this is my fetchSelectedTopics code:

function fetchSelectedTopics(driver,count) {
        describe('',function(){
            it('Topic:: '+count,function(done){
                driver.sleep(2000);
                selectedTopic = driver.findElement(webdriver.By.xpath("//*[@id='selectedModules']/div["+count+"]")).getText().then(function(text){
                    console.log(text);
                    selectedTopics.push(text);
                    //console.log(selectedTopics[i]);
                    //i = Number(i) + 1;
                    done();
                });
            });
        });
}



via user2987322