Saturday 13 May 2017

How to build react-treebeard project

I am a browser based web programmer. For the last few years the simple and straight forward world of javascript development has been turned into a mayhem. For a tiny functionality one has to install a million things with correct versions through cryptic commands and esoteric error messages.

I wanted to use a simple widget at: https://github.com/alexcurtis/react-treebeard

For a week now i have tried to build this project to use but now given up in deep frustration. If I had to list the number of things I have tried it will fill volumes. If someone kind enough can tell me how I can build this project on windows 10 64bit, god bless him/her/other



via Sameer Singh

Node js Cassandra Driver - configure retry policy

Im using the DataStax driver for Cassandra in Node js, and I would like to configure the retry policy I could not find an example, I found a few in Java but noting for Node.

I came across these 2 links but could not derive how to implement this in Node.

http://docs.datastax.com/en/developer/nodejs-driver/3.2/features/tuning-policies/#retry-policy

http://datastax.github.io/nodejs-driver/features/tuning-policies/

Please advise.



via David Faiz

Express creates different session when auth header is changed

I am new to express and I am trying to create session when user logs in to my app.I am using passport for authentication. To login user I am creating basic strategy and on success of basic strategy I am creating a JWT token which I am storing at client side in cookie and I use JWT strategy for subsequent requests.

But I notice that express-session is creating one session when I am logging in which has Basic header and another session for subsequent calls which has JWT header.

Here is my code where I am saving session on login

signin = function(req, res, next) {
    passport.authenticate('basic', function(err, user, info) {
        if (err) { return next(err) }
        if (!user) {
            return res.status(401).json({ error: 'message' });
        }
        var token = jwt.encode({ user: user}, config.db.secret);
        res.cookie('token', token, { maxAge: 900000, httpOnly: true, path: '\/', Secure: true });
        res.status(200).json({ success: true, firstName: user.firstName });
        delete user.password;
        req.session.user = user;
        req.session.save();
    })(req, res, next);
};

But when I debug this code it shows one sessionID in req.sessionID and it show different sessionID in req.sessionID in the following code which as JWT authentication

listProducts = function(req, res) {
    debugger;
    //here req.session.user is undefined which I have saved at login. and sessionID is also different
    res.json({ demo: 'response' });
};

I am expecting it to be same sessionID throughout the life cycle till user logs out of my app. Why is this exactly happening? What is the solution to it?



via nikhil mehta

NodeJS Streaming and Request Module

I have below data coming from an url. Now I want to transform the data into new line delimited JSON using any method that gives me the lowest response time. It is a lot of data and hence streaming made sense to me.

03 Jan 2000,30.00,30.89,29.31,30.89,12487930,,,,

04 Jan 2000,32.30,32.35,29.40,30.38,7095350,,,,

05 Jan 2000,29.90,30.10,28.00,29.20,5044130,,,,

06 Jan 2000,29.50,30.34,29.20,29.41,3988780,,,,

07 Jan 2000,29.20,29.48,27.93,28.50,6264940,,,,

I started with the idea of using res.write and res.end. I have used both axios and request packages for experimental purpose!!!

Attempt#1 Status: Successful, TAT: 1.25s

function streamPrice(req, res) {
  const { url } = req.query;
  res.set({
        "Cache-Control": "no-store, must-revalidate",
        "Connection": "keep-alive",
        "TRANSFER-ENCODING": "chunked"
    });
    axios(url)
        .then(response => {
            const {
                data
            } = response;
            const rawdata = data.split("\n");
            const opLen = rawdata.length;
            for (let i = opLen -1 ; i >=0 ; i--) {
                const cols = rawdata[i].split(",");
                const elem = {
                    date: parseDateEOD(cols[0]),
                    open: +cols[1],
                    high: +cols[2],
                    low: +cols[3],
                    close: +cols[4],
                    volume: +cols[5],
                    bonus: cols[6],
                    dividend: cols[7],
                    rights: cols[8],
                    split: cols[9],
                    absoluteChange: 0,
                    percentChange: 0
                };             
                res.write(JSON.stringify(elem) + "\n\n");
                res.flush();                       
            }
            res.end(null);
            return;
        })
        .catch(e => {
            logger.info(e);
            return;
        });
}

But I am not happy with the response time of 1.25s and want it to be in milliseconds. The mere calling of the data from the url using request takes 45ms so I would like to transform the formatted data back to the client in <250-300ms. Someone suggested using piping increases speed so here is my second attempt using piping

Attempt#2 Status: Successful but no transformation, TAT: 250ms

function streamPrice = function(req,res){
const { url } = req.query;
const reqs = request(url);
reqs.pipe(res);
}

Now I wanted to transform each record and convert it into a newline delimited JSON so I wrote the below:

Attempt#3 Status: Unsuccessful, TAT: 250ms

 function streamPrice = function(req,res){
 const { url } = req.query;
    const reqs = request(url,function(error, response, body){
          const rawdata = body.split("\n");
          const opLen = rawdata.length;
          let result;
          for (let i = opLen - 1; i >= 0; i--) {
            const cols = rawdata[i].split(",");
            const elem = JSON.stringify({
              date: parseDateEOD(cols[0]),
              open: +cols[1],
              high: +cols[2],
              low: +cols[3],
              close: +cols[4],
              volume: +cols[5],
              bonus: cols[6],
              dividend: cols[7],
              rights: cols[8],
              split: cols[9],
              absoluteChange: 0,
              percentChange: 0
            }) + "\n\n";
            if(i===0){
              result = elem;
            } else {
              result+=elem;
            }
          } 
          return result;       
      });
    reqs.pipe(res);
    }

But the resultant data is still the untransformed data set

Few queries: 1. What am I doing wrong? 2. Should I use a transform stream before piping out to res. If yes, can you please help me with the transform stream that would convert the chunks into the below new line delimited JSON format

{"date":"2017-05-12T00:00:00.000Z","open":1562,"high":1562.4,"low":1540.1,"close":1548.85,"volume":28485,"bonus":"","dividend":"","rights":"","split":"","absoluteChange":0,"percentChange":0}

{"date":"2017-05-11T00:00:00.000Z","open":1572.8,"high":1580,"low":1555.15,"close":1561.7,"volume":336193,"bonus":"","dividend":"","rights":"","split":"","absoluteChange":0,"percentChange":0}

{"date":"2017-05-10T00:00:00.000Z","open":1530.95,"high":1575,"low":1528.55,"close":1572.8,"volume":74108,"bonus":"","dividend":"","rights":"","split":"","absoluteChange":0,"percentChange":0}

Please let me know in case of any further information



via Sushanta Deb

Node.js - streaming multiple readable streams to single response

My goal is to stream multiple mongoose cursors (readable) to the same express response (writable).

The problem that I'm facing is that after the first cursor finish, the writable stream gets close event (not finish!) and I can't write to it anymore.

My mongoose model function that is streaming the cursor results to the express response and calculates the count of documents that were streamed is as follows (don't mind the arguments names, these are just for here):

const Promise = require('bluebird');

MongooseSchema.statics.StreamLimitedValues = function (Param1, DateParam, Limit, ExpressResponse) {
    if (0 >= Limit) {
        return Promise.resolve(0);
    }

    let thisRef = this;

    let query = {
        //.... some query
    };

    return new Promise(function (resolve, reject) {
        let count = 0;

        let stream = thisRef.find(query)
            .sort({Date: -1})
            .limit(Limit)
            .lean()
            .cursor({transform: transformFunc}
            );

        function transformFunc (Doc) {
            return JSON.stringify(Doc);
        }

        stream.on('data', (doc) => {
            count++;
        }).on('error', (errInst) => {
            return reject(errInst);
        }).on('end', () => {
            return resolve(count);
        }).pipe(ExpressResponse, {end: false});
    });
};

I'm passing the express response writable object to this function.

I tried to create the same function with ExpressResponse.write(doc) in the on('data') callback instead of pipe, and the results are the same.

This function is called multiple times (sequentially, not parallel) with different parameters and different Limit based on the results of the call to this function before (as you can see I'm returning the count variable in the on('end')).

The problem is that the writable express response close event is emitted after the first call to the function above and I can't write to it anymore.

Any idea of what is happening and how to solve this issue?



via TomG

Typescript can't import files without extension

I am trying to import files in my new Angular2 project. The entry file "main.ts" is able to import an other typescript file using:

import { AppModule }              from './module/app.module';

"app.module.ts" on the other hand is not able to import a ts file without a file extension:

import { AppComponent }             from '../component/app.component';

If I add ".ts" to the file name everything works as expected...

What is my mistake? I assume I am doing everything as per angular guide (https://angular.io/docs/ts/latest/guide/webpack.html)

I have node 6.9.4, npm 4.2.0, typescript 2.3.2, Angular 4.1.0 and Webpack 2.5.1 installed



via donnikitos

Prevent bundling jQuery as a dependency with Browserify

So I have been searching all over the internet to try to find a solution to this problem but I cannot find a solution that works. I'm currently using the latest version of Gulp and Browserify to bundle up JS for the website I'm working on. We previously would concatenate all the JS files together, but I'm moving to a module setup now.

The problem I am running into is duplicating certain dependencies, in this example, I'll focus on jQuery (v2.1.4). Here is my setup:

main.js (Loaded on every page)

window.jQuery = window.$ = require('jquery');
window.Vue = require('vue');    
require('jquery-validation');

// More JS that loads on all pages

page.js (Each page has it's own js file for scripts relating to that page)

require('remodal'); // This requires jQuery

// Rest of the JS for this page...

The problem I am running into is that now jQuery is in both javascript bundles. With Browserify, I marked jQuery as "external" for page-speicific.js which removed jQuery from the script, but I get an error Uncaught Error: Cannot find module 'jquery' and I cannot seem to find a solution to this.

If I "exclude" jQuery with Browserify, or if I put a try block around the require('remodal'), I end up with Uncaught TypeError: $(...).remodal is not a function instead. I'm guessing since the module remodal requires jQuery and it's not loaded there, it's not seeing it's set to the window and that's why execution fails?



via Devin

make api call to get json data

I was trying to get json data from this api, but only thing i'm getting is the html of the page that i would normally get if i opened this link in browser

base url for accessing the api http://sc.productrx.com/public/

Action: Get survey table
HTTP Verb: GET
Rest Resource: schema
Description of parameters, etc: get schema Table name ("survey")

this is what i have tried so far

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

   console.log(req.method+" request received at "+req.url);


request({
     url:"https://sc.productrx.com/public/",
     method:"GET",
     qs:{resource:"schema",data_type:"JSON"}
     },function(err,response,body){
          if(err){
              console.log(err);
              res.status(300).json(error.apiError);
            }
          else{
              console.log(body);
              //var body=JSON.parse(body);
              //res.status(200).json({"success":true,"body":body.users});
            }
        });  });



via Ayush Singh

User permission in Express Rest API and Mongoose

I'm trying to create a rest api project with express and mongodb but I couldn't find a good solution for the role/permission model, should I embed it right into the user model or separate it to another model and is there any good way to implement the role/permission with rest api?



via Le Dinh Nhat Khanh

How can I sort data on Mongodb

Here is data from MongoDB

{
  "urls" : {
    "beauty-credit" : {
      "count" : 1,
      "keyword" : "beauty credit",
      "last_res" : 152,
      "last_sea" : "Sat May 13 2017 15:16:41 GMT+0700 (SE Asia Standard Time)",
      "url_site" : "beauty-credit"
    },
    "etude" : {
      "count" : 2,
      "keyword" : "etude",
      "last_res" : 1048,
      "last_sea" : "Sat May 13 2017 15:16:38 GMT+0700 (SE Asia Standard Time)",
      "url_site" : "etude"
    },
    "skinfood" : {
      "count" : 2,
      "keyword" : "skinfood",
      "last_res" : 478,
      "last_sea" : "Sat May 13 2017 15:16:45 GMT+0700 (SE Asia Standard Time)",
      "url_site" : "skinfood"
    }
  }
}

and Here is my code. Now I filter only last_res > 10

const urls_kws = Object.keys(result)
                    .filter(key => result[key].last_res > 10)

How can I sort data by "count"? Also how can I show only 30 rows?



via Moomoo Soso

Use `index.html` rather than `index.ejs`

I have a mean-stack application. By going to https://localhost:3000/#/home, it reads views/index.ejs. Here is the setting in app.js:

var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.all('/*', function(req, res, next) {
    res.sendFile('index.ejs', { root: __dirname });
});

Actually, I don't use the feature of ejs in index.ejs. So now I want to use just a index.html rather than index.ejs.

I put the content of index.ejs in public/htmls/index.html and views/index.html. And here is the current setting in app.js:

var app = express();
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'ejs');
app.all('/*', function(req, res, next) {
    res.sendFile('index.html', { root: __dirname });
    // res.sendFile('index.html'); // does not work either
});

However, running https://localhost:3000/#/home returns

Error: No default engine was specified and no extension was provided.

Does anyone know how to fix it?



via SoftTimur

Setting up JSDOM with Mocha

I'm trying to use sinon's mock and spy for testing Redux components and async actions, but as soon as I import sinon into any test file, running the following npm script:

mocha --require test/helpers/browser.js --compilers .:babel-core/register --opts test/client/**/*.{js,jsx} --recursive test/client

I get the following error:

TypeError: document.createElement is not a function at .../node_modules/sinon/lib/sinon/util/core/deep-equal.js:3:55

browser.js is where I set up JSDOM:

import { JSDOM } from 'jsdom';

const doc = new JSDOM('<!DOCTYPE html><html><head></head><body></body></html>');
cost win = doc.defaultView; // tried doc.window;

global.document = doc;
global.window = win;

/*
Object.keys(win).forEach(property => {
  if (typeof global[property] === 'undefined') {
    global[property] = win[property];
  }
});
*/

global.navigator = {
  userAgent: 'node.js'
};

I imagine I don't have jsdom set up correctly? I tried looking around and found the commented code in the browser.js file above, but it produces the error when uncommented:

TypeError: Cannot convert undefined or null to object.



via mythereal

Difficulty using babel and jest together

I am trying to use jest and babel together.

Overview

How can I compile a folder of ES6 files with babel, ignore particular folders (/__tests__/) in the build step, and write my tests in ES6 using jest?

More details

My directory structure looks like this:

src
│   a.js
│   b.js
│   c.js
│
└───__tests__
    │   d.js

I wish to compile src (excluding the test folders) and put the output in lib.

Here are the scripts in package.json:

"scripts": {
  "build": "babel src -d lib",
  "test": "jest --coverage"
}

And .babelrc:

{
  "presets": [
    "env"
  ]
}

I have also installed babel-jest, so jest will correctly run my tests written in ES6.

With the configuration above, running yarn build correctly builds into lib, but it also includes the __tests__ folder. yarn test works as expected, correctly running ES6.

I tried:


1.

ignoring the __tests__ folder in .babelrc.

Compilation works as expected, no __tests folder:

yarn build yarn build v0.24.4 $ babel src -d lib src\a.js -> lib\a.js src\b.js -> lib\b.js src\c.js -> lib\c.js Done in 0.82s.

But, yarn test no longer works:

>yarn test
yarn test v0.24.4
$ jest --coverage
 FAIL  src\__tests__\toccer.js
  ● Test suite failed to run

    D:\Dev\toccer\src\__tests__\toccer.js:6
    import toccer from '../'
    ^^^^^^
    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:290:17)
      at process._tickCallback (internal/process/next_tick.js:103:7)

Apparently the ignore option I used above also skips even tranforming the file when jest does its thing.


2.

So, I reverted the change above and tried setting the ignore in the CLI for the build script instead.

"build": "babel src -d lib --ignore '/__tests__/'"

However, the tests folder still gets processed.

>yarn build
yarn build v0.24.4
$ babel src -d lib --ignore '/__tests__/'
src\cli.js -> lib\cli.js
src\index.js -> lib\index.js
src\utils.js -> lib\utils.js
src\__tests__\toccer.js -> lib\__tests__\toccer.js
Done in 0.95s.

This flag seems to do something different from the ignore option in the configuration file. Actually, it doesn't seem to do anything. I tried --ignore '/src/a.js', and it still processed that file. I saw somewhere that there was a bug with babel in an older version, but should be fixed in the version I am currently using.

versions

node: 6.10.0

babel-cli: 6.24.1

babel-jest: 20.0.1

jest-cli: 20.0.1



via Hoten

How can I use async/await in my node v6.10.3 LTS code

I want to use async/await in my node v6.10.3 LTS code for AWS Lambda. However, from what I was reading, Node comes with bundles async/await support from v7.6.0.

How can I go about integrating async await in my code so that when the node version on lambda is upgraded, I would not have to make much(if any) changes.



via Ayush Gupta

Simple Node program produces error only when stepping through it

var animalList = [
    {id_a: "bird", id_b: "t1"},
    {id_a: "dog", id_b: "t2"},
    {id_a: "cat", id_b: "t3"},
    {id_a: "elephant", id_b: "t4"},
];

console.log(test(animalList));

function test(theList) {

   var matchString = "cat"

   var filter = (ele, index) => (ele.id_a === matchString || ele.id_b === matchString); 

   return theList.filter(filter);

}

if I set a break point on var filter = line, and step to the last line I get a "no filter property on undefined" error. If I don't set any break points it runs just fine.

This seems to be a problem with node, rather than the code. But I don't know why. I am using vsCode to debug. With a simple configuration for launching node debugging.

    {
        "type": "node",
        "request": "launch",
        "name": "Launch Program custom",
        "program": "${workspaceRoot}/app.js"
    },



via Volatile

How to scope Firebase in nested promise Cloud Functions (Firebase)

I am trying to set a few variables from Firebase and then pass those into a anotherfunction. Currently, the Promise.all is properly setting foo and bar, but an error is being thrown during the .then, so the response isn't getting set in Firebase.

exports.someFunc = functions.database.ref(`/data`).onWrite(event => {
  const condition = event.data.val()
  if (condition) {
    // Get the data at this location only once, returns a promise, to ensure retrieval of foo and bar
    const foo = event.data.adminRef.child('foo').once('value')
    const bar = event.data.adminRef.child('bar').once('value')

    return Promise.all([foo, bar]).then(results => {
      const foo = results[0].val()
      const bar = results[1].val()

      return someModule.anotherFunction({
        "foo": foo,
        "bar": bar
      }).then(response => {
        // Get an error thrown that Firebase is not defined
        console.log(response);
        let updates = {};
        updates['/data'] = response;
        return firebase.database().ref().update(updates);
      })
    })
  } else {
    console.log('Fail');
  }
});

How can return firebase.database().ref().update(updates); be scoped to set the response from anotherFunction?



via KVNA

Expressjs app started with PM2 in Docker dies with SIGINT

I have a VERY SIMPLE Expressjs app - basically a library wrapper with the single post call.

Here is the app.js conents:

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

var convert = require('./routes/convert');

var app = express();

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

app.use('/', convert);

module.exports = app;

Then I created Dockerfile to containerize the app:

FROM mhart/alpine-node
WORKDIR /src

COPY package.json ./
COPY app.js ./
ADD routes/ ./routes/
ADD bin/ ./bin/

RUN npm i
RUN npm install -g pm2@2.4.0

EXPOSE 3000
CMD ["pm2-docker", "app.js"]

And here is what happens when I try to bring it up (this is with the DEBUG=express:*)

[STREAMING] Now streaming realtime logs for [all] processes
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router:route new /
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router:layer new /
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router:route post /
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router:layer new /
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:application set "x-powered-by" to true
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:application set "etag" to 'weak'
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:application set "etag fn" to [Function: wetag]
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:application set "env" to 'development'
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:application set "query parser" to 'extended'
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:application set "query parser fn" to [Function: parseExtendedQueryString]
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:application set "subdomain offset" to 2
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:application set "trust proxy" to false
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:application set "trust proxy fn" to [Function: trustNone]
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:application booting in development mode
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:application set "view" to [Function: View]
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:application set "views" to '/src/views'
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:application set "jsonp callback name" to 'callback'
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router use / query
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router:layer new /
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router use / expressInit
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router:layer new /
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router use / jsonParser
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router:layer new /
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router use / urlencodedParser
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router:layer new /
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router use / compression
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router:layer new /
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router use / router
2017-05-14-04:15:09 0|app      | Sun, 14 May 2017 04:15:09 GMT express:router:layer new /
2017-05-14-04:15:09 PM2        | App [app] with id [0] and pid [89], exited with code [0] via signal [SIGINT]
2017-05-14-04:15:09 PM2        | Starting execution sequence in -fork mode- for app name:app id:0
2017-05-14-04:15:09 PM2        | App name:app id:0 online

looks like that process dies and being restarted then all the time. I'm not a Node developer just need this one get working and looking forward to any suggestions and help.

Thanks.



via lessless

How to add a short Timeout before each request-promise api call in a loop

So I am new to Promise, I want to use Promise to do multiple url call. Now it seems that the algorithm works but the problem is that the riot api has a rate limit, so I have to let the program wait for a short time after each api call. How should I add this?

var matchidList = [];
                for (var i = 0; i < pml.length; i++) {
                  matchidList.push(pml[i]["gameId"]);
                }

                var matchuri = "https://na1.api.riotgames.com/lol/match/v3/matches/";
                var uris = [];
                for (var i = 0; i < matchidList.length; i++) {
                  uris.push(matchuri + matchidList[i] + "?" + apikey);
                }

                Promise.map(uris, function(url) {
                  return rp.getAsync(url).spread(function(response,body) {
                          return JSON.parse(body);
                  });
                }).then(function(results) {
                     // results is an array of all the parsed bodies in order
                     console.log(results);
                     tag.checkTags("").then((tags) =>{
                       res.render('index', { result: body,
                                             val: search,
                                             matches: ''
                                           });
                     });
                }).catch(function(err) {
                    console.log(err);
                     // handle error here
                });



via Heqian Liu

ionic 2 + google token to POST request to obtain google auth

I've to get token by using @ionic/cloudstorage to obtain user id,data and token.

After i use this token and send to my back-end with post method to send userId and token, I got error and even got error when using postman to send request.

My question, can someone able to explain about this token and how can i use this token to backend (Node.js+express) to auth with googleapis package??

https://developers.google.com/gmail/api/quickstart/nodejs



via PatriotWolf

How to insert multi function into array in javascript

How to push multi function into array stack[]. I using for loop or while loop to push it but it show message error. maybe it must use async. help me. tks. This is a part of my script

var obArr = []
var stack = []
var j,
    count = 0

 while (count < a.length) {
stack.push(function(callback) {
    request(a[count], function(error, response, body) {

        let dom = body
        if (!error) {
            $ = cheerio.load(dom)

        } else {
            console.log('nothing')
        }
        $('.phone_number').each(function() {
            sdt = $(this).text()
        })
        $('.member').each(function() {
            email = $(this).text()
            vl = validateEmail(email)
            if (vl) {
                email = $(this).text()
                email = email.replace(/\s/g, '')
            } else {
                email = ' '
            }
        })
        callback(null, sdt, email)
    })

})
count++
}

// stack.push(getData)
async.parallel(stack, function(err, result) {
    console.log(error)
    console.log(result)
})

}

)



via Bi Li

passport local bad request with middleware controllers and helpers

i have problem with passport-local. see it?

passport.use(new localStrategy(helpPassport.passportLocal)); app.use(passport.initialize());

helpPassport is helper for passport. i use authenticate for middleware ex:

router.post('/signin', passport.authenticate('local', {session : false}), controll.signIn);

controll sign in just for send token jsonwebtoken.

why this token bad request?



via Dyan Kastutara

How to pass a Promise.all return to another function Cloud Functions (Firebase)

I am trying to set a few variables from Firebase and then pass those into a anotherfunction. Currently, the Promise.all is properly setting foo and bar, however, I can't tell if foo and bar are being passed into then, and also Firebase is not properly scoped.

The Promise.all block is based on a tutorial found here: https://www.youtube.com/watch?v=NgZIb6Uwpjc&t=305s

exports.someFunction = functions.database.ref(`/data`).onWrite(event => {
  const condition = event.data.val()
  if (condition) {
    // Get the data at this location only once, returns a promise, to ensure retrieval of foo and bar
    const foo = event.data.adminRef.child('foo').once('value')
    const bar = event.data.adminRef.child('bar').once('value')

    return Promise.all([foo, bar]).then(results => {
      const foo = results[0].val()
      const bar = results[1].val()
      // Properly sets foo and bar
      // As far as I can tell foo and bar are not passed into 'then'
    }).then([foo, bar] => {
      return someModule.anotherFunction({
        "foo": foo,
        "bar": bar
      }).then(response => {
        // Get error thrown that Firebase is not defined
        let updates = {};
        updates[`/data`] = response;
        console.log(response)
        return event.data.adminRef.parent.child('newInfo').update(updates)
      })
    })
  } else {
    console.log('Fail');
  }
});

How can I pass foo and bar into anotherFunction and set the response of that function to Firebase?



via KVNA

MaidSafe browser not able to build 'pack-authenticator'

I am trying to use Maidsafe's latest version of Safe which is the all in one browser. I used the readme in Safe-browserto download and install Safe Browser. But on Step 4 " $ npm run pack-authenticator" terminal fails and outputs this ` Nathans-Air:~ nathanhunsberger$ cd safe_browser Nathans-Air:safe_browser nathanhunsberger$ npm run pack-authenticator

@ pack-authenticator /Users/nathanhunsberger/safe_browser node ./scripts/main.js --authenticator

@ pack-authenticator:unix /Users/nathanhunsberger/safe_browser sh ./scripts/pack_authenticator.sh

beaker-plugin-safe-authenticator@0.1.0 postinstall /Users/nathanhunsberger/safe_browser/authenticator download_deps --package package.json

beaker-plugin-safe-authenticator@0.1.0 build-libs /Users/nathanhunsberger/safe_browser/authenticator node ./build_libs.js "features=mock-routing"

beaker-plugin-safe-authenticator@0.1.0 build-libs:mock /Users/nathanhunsberger/safe_browser/authenticator npm run build-native-mock && npm run build-system-uri

beaker-plugin-safe-authenticator@0.1.0 build-native-mock /Users/nathanhunsberger/safe_browser/authenticator cd ./native/safe_authenticator && cargo clean && cargo update && cargo build --release --features "use-mock-routing" && cd ../../ sh: cargo: command not found npm ERR! file sh npm ERR! code ELIFECYCLE npm ERR! errno ENOENT npm ERR! syscall spawn npm ERR! beaker-plugin-safe-authenticator@0.1.0 build-native-mock: cd ./native/safe_authenticator && cargo clean && cargo update && cargo build --release --features "use-mock-routing" && cd ../../ npm ERR! spawn ENOENT npm ERR! npm ERR! Failed at the beaker-plugin-safe-authenticator@0.1.0 build-native-mock script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/nathanhunsberger/.npm/_logs/2017-05-14T01_33_58_073Z-debug.log npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! beaker-plugin-safe-authenticator@0.1.0 build-libs:mock: npm run build-native-mock && npm run build-system-uri npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the beaker-plugin-safe-authenticator@0.1.0 build-libs:mock script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in: npm ERR! /Users/nathanhunsberger/.npm/_logs/2017-05-14T01_33_58_098Z-debug.log Build Authenticator exited with code 1 npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! beaker-plugin-safe-authenticator@0.1.0 build-libs: node ./build_libs.js "features=mock-routing" npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the beaker-plugin-safe-authenticator@0.1.0 build-libs script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /Users/nathanhunsberger/.npm/_logs/2017-05-14T01_33_58_134Z-debug.log cp: ./dist: No such file or directory Pack Authenticator exited with code 0`

I've updated npm and node.js twice(I think) so I don't understand why this keeps failing. Safe Browser runs fine, but won't authenticate anything, or even let me run "safe-auth://home/#login/" to login.

Any fixes? (if there is somewhere else I should post this, please say so!) Thx!



via nathan Hunsberger

TypeError: THREE.Scene is not a constructor

I'm having trouble getting a framework using three.js to work for an assignment. I've cloned this repository and used npm install to download the dependencies. When I run the server and load the page I get TypeError: THREE.FileLoader is not a constructor.

This seems to be because there is no FileLoader file but I don't know how to fix the issue - I tried deleting the contents of node_module/three and replacing it with the up-to-date three.js repository, but that gave me Uncaught Error: Cannot find module "three".

I don't know why running npm install didn't give me the updated version of three.js and gave me code that won't run. How do I fix my problem?



via user2260199

Why flatten isn't working?

I have read the code in how to flatten an array in MDN in JS. And works fine, but I don't understand why isn't working in this case:

const data = [null, ['a', 'b', 'c']]
const flattened = data.reduce((acc, cur) => {
    if(null != cur)
        acc.concat(cur)
}, [])

And this error:

TypeError: Cannot read property 'concat' of undefined

How to correct this?



via Lucas Almeida Carotta

Error installing polybuild with npm

I have installed gulp and bower using command "npm install -g gulp bower", and installed npm and bower on the root folder of my project using commands "npm install" and "bower install". I have node v7.10.0 npm v4.2.0 and gulp version 3.9.1(both CLI and Local Version). When I run 'gulp serve' on the root directory of my project I kept on getting messages "Cannot find module 'moduleName'" I kept on installing the modules as I got error messages using command "npm install --save moduleName", now when I got the error "Cannot find module 'polybuild'", I tried to install polybuild but it failed. I have searched for similar polybuild installation errors on the net like I did with other missing modules but couldn't find. I have attached the images below taken from the command line.Running 'gulp serve' Installing polybuild



via Lesedi

How to use html-minifier npm module?

I want to minify my html files from node.js using this module https://www.npmjs.com/package/html-minifier

I have this code

                // minify the html code
                fse.readFile(filename, function(err, data) {
                    if (err) return console.error(err);
                    var result = minify(data.toString(), {
                        removeAttributeQuotes: false
                    });
                    console.log(result);
                });

However it logs the same code as from the original file. It didn't minify it. Does anyone know what's wrong?

Thanks



via omega

Unable to create a HTTPS server with Node.js, socket.IO and Express

I'm not too familiar with Javascript but I'm on a run now because I have been assigned an assignment for academic purposes to create a Live Streaming website application using WebRTC.

I have been following the Codelab tutorial, but since it uses an HTTP server it really won't work in Chrome (my guess, not really sure about it since it works on Firefox).

I would like to know how could I make this server a HTTPS server and how could I access to it using the nat network or my public router ip address (if it's possible) instead of the localhost. I've already generated my .key and my .crt.

These are the codes by Codelab:

index.js (server)

'use strict';

var os = require('os');
var nodeStatic = require('node-static');
var http = require('http');
var socketIO = require('socket.io');

var fileServer = new(nodeStatic.Server)();
var app = http.createServer(function(req, res) {
  fileServer.serve(req, res);
}).listen(8080);

var io = socketIO.listen(app);
io.sockets.on('connection', function(socket) {

  // convenience function to log server messages on the client
  function log() {
    var array = ['Message from server:'];
    array.push.apply(array, arguments);
    socket.emit('log', array);
  }

  socket.on('message', function(message) {
    log('Client said: ', message);
    // for a real app, would be room-only (not broadcast)
    socket.broadcast.emit('message', message);
  });

  socket.on('create or join', function(room) {
    log('Received request to create or join room ' + room);

    var numClients = io.sockets.sockets.length;
    log('Room ' + room + ' now has ' + numClients + ' client(s)');

    if (numClients === 1) {
      socket.join(room);
      log('Client ID ' + socket.id + ' created room ' + room);
      socket.emit('created', room, socket.id);

    } else if (numClients === 2) {
      log('Client ID ' + socket.id + ' joined room ' + room);
      io.sockets.in(room).emit('join', room);
      socket.join(room);
      socket.emit('joined', room, socket.id);
      io.sockets.in(room).emit('ready');
    } else { // max two clients
      socket.emit('full', room);
    }
  });

  socket.on('ipaddr', function() {
    var ifaces = os.networkInterfaces();
    for (var dev in ifaces) {
      ifaces[dev].forEach(function(details) {
        if (details.family === 'IPv4' && details.address !== '127.0.0.1') {
          socket.emit('ipaddr', details.address);
        }
      });
    }
  });

  socket.on('bye', function(){
    console.log('received bye');
  });

});

packaje.json (in case the code is needed)

{
  "name": "webrtc-codelab",
  "version": "0.0.1",
  "description": "WebRTC codelab",
  "dependencies": {
    "node-static": "0.7.7",
    "socket.io": "1.2.0"
  }
}

My attempt of HTTPS server

'use strict';

var os = require('os');
var express = require('express');
var nodeStatic = require('node-static');
var http = require('http');
var https = require('https');
var fs = require('fs');
var socketIO = require('socket.io');

var options = {
  key: fs.readFileSync('host.key'),
  cert: fs.readFileSync('host.cert')
};


var fileServer = new(nodeStatic.Server)();
var app = express();
//http.createServer(app).listen(80);

http.createServer(app,function(req,res){
    fileServer.serve(req,res);
}).listen(80);

https.createServer(options,app,function(req,res){
    fileServer.serve(req,res);
}).listen(443);

//var app = http.createServer(function(req, res) {
//  fileServer.serve(req, res);
//}).listen(8080);

var io = socketIO.listen(app);
io.sockets.on('connection', function(socket) {

  // convenience function to log server messages on the client
  function log() {
    var array = ['Message from server:'];
    array.push.apply(array, arguments);
    socket.emit('log', array);
  }

  socket.on('message', function(message) {
    log('Client said: ', message);
    // for a real app, would be room-only (not broadcast)
    socket.broadcast.emit('message', message);
  });

  socket.on('create or join', function(room) {
    log('Received request to create or join room ' + room);

    var numClients = io.sockets.sockets.length;
    log('Room ' + room + ' now has ' + numClients + ' client(s)');

    if (numClients === 1) {
      socket.join(room);
      log('Client ID ' + socket.id + ' created room ' + room);
      socket.emit('created', room, socket.id);

    } else if (numClients === 2) {
      log('Client ID ' + socket.id + ' joined room ' + room);
      io.sockets.in(room).emit('join', room);
      socket.join(room);
      socket.emit('joined', room, socket.id);
      io.sockets.in(room).emit('ready');
    } else { // max two clients
      socket.emit('full', room);
    }
  });

  socket.on('ipaddr', function() {
    var ifaces = os.networkInterfaces();
    for (var dev in ifaces) {
      ifaces[dev].forEach(function(details) {
        if (details.family === 'IPv4' && details.address !== '127.0.0.1') {
          socket.emit('ipaddr', details.address);
        }
      });
    }
  });

  socket.on('bye', function(){
    console.log('received bye');
  });

});

The error is when I try: var io = socketIO.listen(app); and I don't really know why it works with only the http, and not with both the http and https server created in app.

I would really appreciate your help!



via maga

How to get a variable from a JS file to a node JS file

So essentially what I'm trying to do is get a variable from my app.js file to my run.js file. The app.js file handles everything client related, and the run.js handles server side stuff. So I've tried using 'export' and 'require' but that still doesn't seem to be helping because I keep getting this error...

ReferenceError: module is not defined

This is essentially what I've tried to do, the currentUser in the app.js is already defined.

//app.js
module.currentUser = currentUser;

//run.js
var myApp = require('./app.js');
var user = myApp.currentUser;



via Elmer.V

$http.get request is only successful on first page load

Here's the scenario: a user visits http://localhost:3000/all, and a list of all users are displayed on the page. Great, that's what I want. But, when I refresh the page, I lose everything (no HTML is rendered). I'm just left with a raw JSON output that is being returned by the server.

The relevant sections of my Angular file:

var app = angular.module('social', ['ngRoute', 'ngCookies', 'ui.router'])

app.config(function($routeProvider, $locationProvider, $stateProvider, $urlRouterProvider) {
    $routeProvider
   .when('/', {
    templateUrl: 'home.html',
    controller: 'HomeController'
    })
   .when('/login', {
    templateUrl: 'login.html',
    controller: 'LoginController'
    })
   .when('/signup', {
    templateUrl: 'signup.html',
    controller: 'SignupController'
    })
   .when('/about', {
    templateUrl: 'about.html'
    })
   .when('/profile', {
    templateUrl: 'profile.html',
    controller: 'UserProfileController',
   })
   .when('/all', {
    templateUrl: 'members.html',
    controller: 'MembersController',
    resolve: {
        allMembers: function($http) {
            return $http.get('/all').then(function(res) {
                return res.data
            })
        }
    }
   })
   $locationProvider.html5Mode(true)
})

app.controller('MembersController', function($http, $scope, $cookies) {
    function getAllUsers() {
        $http.get('/all').then(function(res) {
            $scope.members = res.data
        })
    }
    getAllUsers()
})

You'll notice I attempted to use resolve in app.config, but that didn't help (I'm probably using it incorrectly). When using resolve, my controller becomes:

app.controller('MembersController', function(allMembers, $scope) {
    $scope.members = allMembers
})

I get the same result: data loads fine on initial page load, but upon refresh, I'm left with raw JSON on the page.

The relevant part in the server (using Mongoose):

app.get('/all', function(req, res, next) {
    User.find(function(err, users) {
        if (err) console.log(err)
        return res.json(users)
    })
})

Could anyone tell me what I'm doing wrong? I followed an online tutorial before trying this on my own, and it worked fine in the tutorial (obviously).



via Farid

Node.js Debugger Protocol without Chrome

I was taking a look at debugging Node.js and it seems the old protocol is deprecated in favor of the newer one. Unfortunately, all examples on new protocol uses Chrome and I don't want to use Chrome. I plan to develop my own debugger front end.

I will appreciate anyone point me to the right direction on this. Simple example will or documentation with example will be great!



via Stefano Mtangoo

How can I check and query a document using mongoose?

I have an userSchema and fileSchema. In file schema, I have fields like owner(ref: user) and field hasAccess(ref: user) - array of users something like this:

const FileSchema = new Schema({
    filename: String,
    filesize: Number,
    owner: {type: Schema.Types.ObjectId, ref: 'User'},
    hasAccess: [{type: Schema.Types.ObjectId, ref: 'User'}],
    createdAt: {type: Date, default: Date.now}
});


const UserSchema = new Schema({
    username: String,
    password: String,
    passphrase: String,
    files: [{type: Schema.Types.ObjectId, ref: 'File' }],
    createdAt: {type: Date, default: Date.now}
});

I have a route:

.get('/file/:id', [isLoggedIn], function (req, res) {
            const user = req.user,
                fileId = req.params.id;
            File
                .findOne({_id: fileId})
                .populate('hasAccess')
                .exec(function (err, file) {
                    if (err) {
                        console.log(err);
                        return res.redirect("/error");
                    }
                    //check here if user is owner OR user in hasAccess array 
                });
        })

There I query a file by Id and then check if a user has rights to this file. To check if user it's enough file.owner == user._id But what about hasAccess field should I iterate each object and compare it with current user id? Or is it possible make a query without any further comparison?



via Haygo

Failed to send email from my desire domain using nodemailer

I am writing script to send email from my domain using nodmailer package, my code is below:-

    /************send email **************/



 var nodemailer = require('nodemailer');
         var transporter = createTransport('smtp://admin@digieasynow.com:paxxxxxxxxx
         @mail.digieasynow.com');
         var mailOptions = {
         from: '"Tester 👥" admin@digieasynow.com', 
         to: 'example@gmail.com', 
         subject: 'Hello ✔', 
         text: 'Hello world 🐴', 
         html: 'Hello world 🐴' 
        };
        transporter.sendMail(mailOptions,function(error, info){
        if(error){
        return console.log(error);
        }
        console.log('Message sent: ' + info.response);
        });


        /**End code here************/

On running it gives below error..........................

Error: Hostname/IP doesn't match certificate's altnames: "Host: mail.digieasynow.com. is not in the cert's altnames: DNS:.webhostbox.net, DNS:webhostbox.net"

Please help....................



via amish ges

Express App broken for unknown reason

I'm really confused my express app was working just fine until I made some modifications and everything is now broken. I checked out to a previous commit when everything was working but it's still broken.

I get this error in the browser :

localhost/:1 GET http://localhost:3000/styles.bundle.css/ 
localhost/:1 GET http://localhost:3000/bootstrap-social.css/ 
localhost/:1 GET http://localhost:3000/font-awesome.css/ 
localhost/:1 GET http://localhost:3000/custom.css/ 
localhost/:1 GET http://localhost:3000/app.bundle.js/ 
localhost/:1 GET http://localhost:3000/mainClient.js/ 
localhost/:1 GET http://localhost:3000/register.js/ 404 (Not Found)

Files are not found, here's my server log :

[0] GET / 304 47.615 ms - -
[0] GET /styles.bundle.css/ 404 0.928 ms - 157
[0] GET /bootstrap-social.css/ 404 0.578 ms - 160
[0] GET /font-awesome.css/ 404 1.283 ms - 156
[0] GET /custom.css/ 404 0.910 ms - 150
[0] GET /app.bundle.js/ 404 1.455 ms - 153
[0] GET /mainClient.js/ 404 1.651 ms - 153
[0] GET /register.js/ 404 2.128 ms - 151

I don't know why it started adding those "/" at the end of paths... Does anyone has an idea of what's going on ?

Note: I was trying to implement connect-history-api-fallback to use my VueRouter on a single page. But I really don't understand why the problem would persist after a git rollback !



via Martin B

Is it possible to make socket.io work with phonegap?

I've been trying many different approaches including connecting to my node.js server from an external app made with phonegap and node but even after setting my CORS it still failed to connect to socket.io, anyone got a suggestion?



via Doomer

Does it makes any difference from module caching perspective how it is required?

Im trying to understand module caching. I've read lots of materials but it's still fuzzy because I can't find a good article that goes to full details and there are some contrary opinions going around the web.

const modules = {
  first: require('./modules/first.js'),
  second: require('./modules/second.js')
};

// vs

const first = require('./modules/first.js');
const second = require('./modules/second.js');

Does these two have any difference when it comes to caching (both are exported same way)?



via Solo

How do I exit node from my script?

In my script, I want to be able to quit node without doing it manually (CTRL-C), however process.exit() does not seem to work?

I tried a few different things but is this because I still have an active stream open? How would i go about closing all active streams?

var fs = require('fs'),
readline = require('readline');


var count = 0;

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});


process.stdin.on('data', function(data){ 

  console.log(data);
  process.stdin.destroy();

})

rl.on('line', function(line){
  count++;
  rl.close();
})


function getBytes(data){
   return Buffer.byteLength(data, 'utf8');
}




process.stdin.on('close', function(){
  console.log(getBytes(count));
  process.exit();
})



via sagnew

sequelize can't hash password

I am having a issue trying to hash password using bcrypt-nodejs with sequelize, when i route to my register i don't get any response and no register is added to my database :/.

So my model is this:

    "use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');

module.exports = function (sequelize, DataTypes) {
  var User = sequelize.define("User", {
    username: DataTypes.STRING,
    email: DataTypes.STRING,
    password: DataTypes.STRING
  }, {
      instanceMethods: {
        generateHash: function (password) {
          return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },
        validPassword: function (password) {
          return bcrypt.compareSync(password, this.password);
        }
      },


    });

  return User;
}

on my register route i try to hash the password and assing it to my password field like this:

var express = require('express');
var User = require('../../models').User;
var router = express.Router();

/* GET users listing. */
router.post('/', function (req, res, next) {
 console.log("hi");
  if (JSON.stringify(req.body) == "{}") {
    return res.status(400).json({ Error: "Register request body is empty" });
  }
  if (!req.body.email || !req.body.username || !req.body.password) {
    return res.status(400).json({ Error: "Missing fields for registration" });
  }
console.log(req.body.password);
  var password = User.generateHash(req.body.password);
  console.log(password);

  User.create({
    username: req.body.username,
    email: req.body.email,
    password: password
  }).then(function () {
    return res.status(200).json({message: "user created"});
  })

});

module.exports = router;

as i said i don't get any response from postman to the register route and nothing get added in the database, the problem just occurs when i add password, without the password field, the register get added :/.

thank you :)



via Antonio Costa

DynamoDB Table query items using global secondary index

I am trying to query a dynamo table with latitude and longitude for various locations. I want to get the values between certain coordinates as a user pans on the map.

The primary key for the table is city and the sort key is id. I created a global secondary index with lat as the partition key and lon as the sort key (to query for locations between two points in latitude and longitude).

I am trying to use this query:

let doc = require('dynamodb-doc');
let dynamo = new doc.DynamoDB();

...

        var params = {
            TableName : "locations-dev",
            IndexName: "lat-lon-index",
            KeyConditionExpression: "lon between :lon2 and :lon1 AND lat between :lat1 and :lat2",
            ExpressionAttributeValues: {
                ":lat1": JSON.stringify(event.bodyJSON.east),
                ":lat2": JSON.stringify(event.bodyJSON.west),
                ":lon1": JSON.stringify(event.bodyJSON.north),
                ":lon2": JSON.stringify(event.bodyJSON.south)
            }
        };

        dynamo.query(params, function (err, data) {
            if (err) {
                console.error('Error with ', err);
                context.fail(err);
            } else {
                context.succeed(data);
            }
        });

But I am getting this error:

{
   "errorMessage": "Query key condition not supported",
   "errorType": "ValidationException",
   "stackTrace": [
    ...
  ]
 }

Here is an example item in Dynamo:

{
  "id": "18",
  "lat": "39.923070",
  "lon": "-86.036178",
  "name": "Home Depot",
  "phone": "(317)915-8534",
  "website": "https://corporate.homedepot.com/newsroom/battery-recycling-one-million-pounds"
}



via Rose

Express.js - Connect with GraphQL external API

I have problem with connect to external API (GraphQL) on Express.js . Can You give me a some good tutorials about this?

And one more question. I have this error:

Link to error message - img

It's possible to connect with this API ?



via Jakub Gadawski

node-libcurl obtaining wrong IP address on POST

I'm new to nodejs so this may be operator error, but I'm trying to make a POST request to PayPay's test URL. I tried using http request in nodejs, but got an odd response. I was able to get curl on the command line to work, so I figured I'd use curl in node.

When I run the following curl command in bash it works:

curl -v --data "USER=myLogin&VENDOR=myLogin&PARTNER=PayPal&PWD=QQQQQQQQQ&CREATESECURETOKEN=Y&SECURETOKENID=fb7810e9-252b-4613-a53b-6432148bfd97&TRXTYPE=S&AMT=100.00" https://pilot-payflowpro.paypal.com

I get the following results (I know the secure token was used, but its a sign the curl call worked):

* Rebuilt URL to: https://pilot-payflowpro.paypal.com/
*   Trying 173.0.82.163...
* Connected to pilot-payflowpro.paypal.com (173.0.82.163) port 443 (#0)
* found 173 certificates in /etc/ssl/certs/ca-certificates.crt
* found 704 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / RSA_AES_256_CBC_SHA256
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: pilot-payflowpro.paypal.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3*    subject: C=US,ST=California,L=San Jose,O=PayPal\, Inc.,OU=Payflow Production,CN=pilot-payflowpro.paypal.com
*    start date: Wed, 08 Feb 2017 00:00:00 GMT
*    expire date: Thu, 28 Feb 2019 23:59:59 GMT
*    issuer: C=US,O=Symantec Corporation,OU=Symantec Trust Network,CN=Symantec Class 3 Secure Server CA - G4
*    compression: NULL
* ALPN, server did not agree to a protocol
> POST / HTTP/1.1
> Host: pilot-payflowpro.paypal.com
> User-Agent: curl/7.47.0
> Accept: */*
> Content-Length: 179
> Content-Type: application/x-www-form-urlencoded
> 
* upload completely sent off: 179 out of 179 bytes
< HTTP/1.1 200 OK
< Connection: close
< Server: VPS-3.033.00
< Date: Sat, 13 May 2017 20:13:38 GMT
< Content-type: text/namevalue
< Content-length:    121
< 
* Closing connection 0
RESULT=7&RESPMSG=Field format error: Secure Token Id already beenused&SECURETOKENID=fb7810e9-252b-4613-a53b-6432148bfd97e

I then use the following nodejs code (in a method exposed through Express as a GET):

var newSId = uuid.v4();
var curl = new Curl();
var url = 'https://pilot-payflowpro.payapl.com/';
var data = {
  'USER': 'myLogin',
  'VENDOR': 'myLogin',
  'PARTNER': 'PayPal',
  'PWD': 'QQQQQQQQQQQ',
  'CREATESECURETOKEN': 'Y',
  'SECURETOKENID': newSId,
  'TRXTYPE': 'S',
  'AMT': '100.00'
};

data = qstr.stringify(data);

console.log("Data = " + data);

curl.setOpt(Curl.option.URL, url);
curl.setOpt(Curl.option.POSTFIELDS, data);
curl.setOpt(Curl.option.POST, 1);
curl.setOpt(Curl.option.VERBOSE, true);

curl.perform();

curl.on('end', function(statusCode, body){
   this.close();
});

curl.on('error', curl.close.bind(curl));

When I execute the GET via a browser I get the following information dumped to console:

Data = USER=myLogin&VENDOR=myLogin&PARTNER=PayPal&PWD=QQQQQQQQ&CREATESECURETOKEN=Y&SECURETOKENID=4b8f0763-2d09-4c2a-a57e-f5a4dc5be744&TRXTYPE=S&AMT=100.00
*   Trying 209.15.13.134...
* connect to 209.15.13.134 port 443 failed: Connection refused
* Failed to connect to pilot-payflowpro.payapl.com port 443: Connection refused
* Closing connection 0

For a reason I can't explain, in the node-libcurl call, a different IP address is being used. The curl command line call uses: 173.0.82.163, but node-libcurl uses: 209.15.13.134. I'm curious why. If there is a way I should have debugged this better, please let me know.

Thanks in advance!



via turnip_cyberveggie

Node.js removing element from associated element

I added a feature where users can pin recipes to their profile. However, when the recipe is deleted, the recipe isn't removed from the user's pinnedRecipes, even though it doesn't appear on the user's show page (the ID stays in the user's pinnedRecipes in the database).

Here's the association between the Recipes and the user's pinnedRecipes:

var userSchema = new mongoose.Schema({
    username: String,
    password: String,
    admin: {type:Boolean, default: false},
    bio: {type:String, default: "Cet utilisateur n'a pas encore rempli cette section."},
    profileImage: {type:String, default: "http://www.wilwia.com/images/default-user.png"},
    pinnedRecipes:[
        {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Recipe"
        }
    ]
});

var recipeSchema = new mongoose.Schema({
    title: String,
    source: String,
    image: String,
    preplength: String,
    cooklength: String,
    portions: Number,
    description: String,
    ingredients: String,
    instructions: String,
    createdAt: { type: Date, default: Date.now },
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String,
    },
    comments: [
            {
                type: mongoose.Schema.Types.ObjectId,
                ref: "Comment"
            }
        ],
    category: {type:String, enum: ['appetizer', 'salad', 'soup', 'meat', 'pasta', 'breakfast', 'dessert']}
});

Here's what I tried, that didn't work (everything works, except removing recipe from pinnedRecipes):

    //DESTROY ROUTE
router.delete("/:id", middleware.checkRecipeOwnership, function(req, res){
    Recipe.findById(req.params.id, function(err, foundRecipe){
        if(err){
            res.redirect("back");
        } else {
            //delete associated comments
            if(foundRecipe.comments.length > 0){
                Comment.remove({
                _id: {
                    $in: foundRecipe.comments
                }
            }, function(err){
                if(err){
                    console.log(err);
                }
            });
            //delete from every user's pinned recipes
            User.find({pinnedRecipes: "ObjectId(" + foundRecipe._id + ")"}, function(err, foundUsers){
                if(err){
                    console.log(err);
                } else {
                    console.log(foundUsers);
                    foundUsers.forEach(function(user){
                        user.pinnedRecipes.remove(foundRecipe);
                        user.save();
                    });
                }
            });
            //remove the campground
            foundRecipe.remove(function(err, recipe){
               if(err){
                   console.log(err);
                   res.redirect("/recipes");
               } else {
                   res.redirect("/recipes");
               }
            });
            }
        }
    });
});

Also, here's how recipes are pinned:

// PIN ROUTE
router.get("/pin/:id", middleware.isLoggedIn, function(req, res){
    Recipe.findById(req.params.id, function(err, foundRecipe){
        if(err){
            req.flash("error", "Une erreur s'est produite.");
            res.redirect("/recipes/" + foundRecipe._id);
        } else {
            User.findById(req.user._id, function(err, user){
                if(err){
                    req.flash("error", "Une erreur s'est produite.");
                    res.redirect("/recipes/" + foundRecipe._id);
                } else { 
                  user.pinnedRecipes.push(foundRecipe);
                  user.save();
                  res.redirect("/recipes/" + foundRecipe._id);
                  req.flash("success", "Pinned recipe"); 
                }
            });
        }
    });
});

// UNPIN ROUTE
router.delete("/pin/:id", middleware.isLoggedIn, function(req, res){
    Recipe.findById(req.params.id, function(err, foundRecipe){
        if(err){
            req.flash("error", "Une erreur s'est produite.");
            res.redirect("/recipes/" + foundRecipe._id);
        } else {
            User.findById(req.user._id, function(err, user){
                if(err){
                    req.flash("error", "Une erreur s'est produite.");
                    res.redirect("/recipes/" + foundRecipe._id);
                } else { 
                  user.pinnedRecipes.remove(foundRecipe);
                  user.save();
                  res.redirect("/recipes/" + foundRecipe._id);
                  req.flash("success", "Pinned recipe"); 
                }
            });
        }
    });
});

Thanks a lot!



via Davycodes

Login system using Passport.js is always executing “failureRedirect” (nodejs)

I'm doing a tutorial and I'm stuck in the login area. When I'm login in with Passport.js it always executing "failureRedirect" in authenticate.

After trying to debug replacing the router.post('login') route I received the following message:

Error: null User: false Info: {"message":"Missing credentials"}

After Reading on some forums I think that the problem could be related to body-parser. I've been trying to solve the problem but I haven't been able yet. I'd appreciate the help of a most experienced node.js programmer.

The structure of the project is: app.js routes: users.js models: user.js

user.js

var express = require('express');
var router = express.Router();
var multer = require('multer');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');

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

var upload = multer({ dest: './uploads' });

// create application/json parser
var jsonParser = bodyParser.json();

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/register', function(req, res, next) {
  res.render('register', {
    title: 'Register'
  });
});

router.get('/login', function(req, res, next) {
  res.render('login', {
    'title': 'Login'
  });
});

router.post('/register', upload.single('profileimage'), function (req, res, next) {
  //Get Form Values
  var name = req.body.name;
  var email = req.body.email;
  var username = req.body.username;
  var password = req.body.password;
  var password2 = req.body.password2;


  // Check for Image Field
  if(req.files && req.files.profileimage){
    console.log('Uploading File...');

    // File Info
    var profileImageOriginalName = req.files.profileimage.originalname;
    var profileImageName = req.files.profileimage.name;
    var profileImageMime = req.files.profileimage.mimetype;
    var profileImagePath = req.files.profileimage.path;
    var profileImageExt = req.files.profileimage.extension;
    var profileImageSize = req.files.profileimage.size;
  } else {
    // Set a Default Image
    var profileImageName = 'noimage.png';
  }

  // Form Validation
  req.checkBody('name', 'Name field is required').notEmpty();
  req.checkBody('email', 'Email field is required').notEmpty();
  req.checkBody('email', 'Email not valid').isEmail();
  req.checkBody('username', 'Username field is required').notEmpty();
  req.checkBody('password', 'Password field is required').notEmpty();
  req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

  // Check for errors
  var errors = req.validationErrors();

  if(errors){
    res.render('register', {
      errors: errors,
      name: name,
      email: email,
      username: username,
      password: password,
      password2: password2
    });
  } else {
    var newUser = new User({
      name: name,
      email: email,
      username: username,
      password: password,
      profileImage: profileImageName
    });

    // Create User
    User.createUser(newUser, function (err, user) {
      if(err) throw err;
      console.log(user);
    });

    //Success Message
    req.flash('success', 'You are now registered and may log in');

    res.location('/');
    res.redirect('/');
  }
});

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.getUserById(id, function(err, user) {
    done(err, user);
  });
});

passport.use(new LocalStrategy(
  function (username, password, done) {
    User.getUserByUsername(username, function (err, user) {
      if(err) throw err;
      if(!user){
        console.log('Unknown User');
        return done(null, false, {message: 'Unknown User'});
      }

      User.comparePassword(password, user.password, function (err, isMatch) {
        if(err) throw err;
        if(isMatch){
          return done(null, user);
        } else {
          console.log('Invalid Password');
          return done(null, false, {message:'Invalid Password'});
        }
      });
    });
  }
));

router.post('/login', jsonParser, passport.authenticate('local', {
  successRedirect: '/',
  failureRedirect: '/users/login',
  failureFlash: true //'Invalid username or password'
}), function (req, res) {
  console.log('Authentication Successful');
  req.flash('success', 'You are logged in');
  res.redirect('/');
});

router.post('/login', passport.authenticate('local', function(err, user, info) {
  console.log("authenticate");
  console.log(err);
  console.log(user);
  console.log(info);
}), function (req, res) {
  console.log('Authentication Successful');
  req.flash('success', 'You are logged in');
  res.redirect('/');
});

module.exports = router;

user.js

var mongoose = require('mongoose');
var bcrypt = require('bcrypt');

mongoose.connect('mongodb://localhost/nodeauth');

var db = mongoose.connection;

// User Schema
var UserSchema = mongoose.Schema({
  username: {
    type: String,
    index: true
  },
  password: {
    type: String,
    required: true,
    bcrypt: true
  },
  email: {
    type: String
  },
  name:{
    type: String
  },
  profileimage:{
    type: String
  }

});

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

module.exports.comparePassword = function(candidatePassowrd, hash, callback) {
  bcrypt.compare(candidatePassowrd, hash, function (err, isMatch) {
    if(err) return callback(err);
    callback(null, isMatch);
  });
}

module.exports.getUserById = function (id, callback) {
  User.findById(id, callback);
}

module.exports.getUserByUsername = function (username, callback) {
  var query = {username: username};
  User.findOne(query, callback);
}

module.exports.createUser = function (newUser, callback) {
  bcrypt.hash(newUser.password, 10, function (err, hash) {
    if(err) throw err;

    // Set hashed pw
    newUser.password = hash;

    // Create User
    newUser.save(callback);
  });
}

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// Handle File Uploads
// app.use(multer({dest:'./uploads'}));
var upload = multer({ dest: './uploads' });

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));

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

// Handle Express Sessions
app.use(session({
  secret: 'secret',
  saveUninitialized: true,
  resave: true
}));

// Passport
app.use(passport.initialize());
app.use(passport.session());

// Validator
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
    var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));
// app.use(expressValidator({
//   errorFormatter
// }));

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(flash());
app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Thanks for your help :)



via Rafa

How to connect to a socket.io room from another server node.js

I cant seem to find a socket.io method that would do this.

I'm trying to create a "finding a game" system that would grab player from an array then put them in a room that's open.

index.js:

// Put user in find a game queue.
socket.on('bsb2v2find', function(data){
    bsb2v2finding.push(data);
    userdata = data;
});
// Server gets an update that there's an open server.
socket.on('bsb2v2opnrm', function(room){
    if(bsb2v2finding.length >= 4 && bsb2v2finding.filter(function(player){ return player.username ===  userdata.name}).length){
        var players = [];
        repeatLoop(4, function(){
            players.push(bsb2v2finding.shift());
        });
        repeatLoop(4, function(i){
            // This is where all player connect to a room on the game port. 
            players.socket.join(room);
        });
    }
});

function repeatLoop(num, callback){
    for(var i = 0;i !== num;i++){
        callback(i);
    }
}



via Korbin Deary

Should I use an ORM for guest mode? temporary/persistent data

I am currently developing a single page JS app. It will pull in/store data from a REST API.

My plan was that the user would register, then login, When they change the data it updates their info in the db. when they later login, the app would populate the interface with their data from the database via the api and also allow it to be updated.

However I have now decided that I would like a guest mode. So that initially when the app loads the user can fully use the app, set data, update data. see the results. But not need to register. If they then register it stores what they have done. Associates the work with the created user account so that they can login and have it load as usual.

I am now trying to decide how this would be done. Should I use an ORM?, that way both guest and registered would run through the same interface except the registered would persist?

Any suggestions would be welcome



via Elbolton

frontend and backend separation in azure

I'm developing a simple site consisting of an Angular frontend and a simple NodeJS backend. I currently see 3 ways to setup the project:

  • have 1 Web App to serve the static HTML and 1 Web App for the NodeJS backend
  • serve both REST API and static files using the same NodeJS instance
  • I read about virtual directories for Azure Web Apps, but wasn't able to find appropriate documentation. Is that even a viable solution?

What's the standard setup to use for Azure? Is there any in-depth documentation I missed?



via Michael

Using PostCSS Lost grid with SASS throws a weird message

I am trying to use Lost grid with SASS in my gulp workflow. I installed gulp-postcss, gulp-sass and lost grid from npm and setup all things perfectly. Everything works well, but it shows the below message every time I start the gulp server:

Node#moveTo was deprecated. Use Container#append.

Everything works properly, but what does this mean? Is this an error message?



via user7674441

Node.js FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

SO: Windows 10 API: Laravel 5.4 Laravel-Mix: 0.10.0 Node v7.10.0 Npm v4.2.0 Command Prompt: PowerShell

Command Run: "npm run dev"

also gave me this error with run watch, hot and production

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

Error Image

0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'dev' ]
2 info using npm@4.2.0
3 info using node@v7.10.0
4 verbose run-script [ 'predev', 'dev', 'postdev' ]
5 info lifecycle @~predev: @
6 silly lifecycle @~predev: no script for predev, continuing
7 info lifecycle @~dev: @
8 verbose lifecycle @~dev: unsafe-perm in lifecycle true
9 verbose lifecycle @~dev: PATH: C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin;C:\igsm-web\node_modules\.bin;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\7-Zip;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\xampp\php;C:\ProgramData\ComposerSetup\bin;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Program Files (x86)\Microsoft VS Code\bin;C:\Users\Trucco Pedro\AppData\Roaming\Composer\vendor\bin;C:\Users\Trucco Pedro\AppData\Roaming\npm
10 verbose lifecycle @~dev: CWD: C:\igsm-web
11 silly lifecycle @~dev: Args: [ '/d /s /c',
11 silly lifecycle   'node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js' ]
12 silly lifecycle @~dev: Returned: code: 3  signal: null
13 info lifecycle @~dev: Failed to exec dev script
14 verbose stack Error: @ dev: `node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
14 verbose stack Exit status 3
14 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\lib\utils\lifecycle.js:279:16)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at EventEmitter.emit (events.js:194:7)
14 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\lib\utils\spawn.js:40:14)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at ChildProcess.emit (events.js:194:7)
14 verbose stack     at maybeClose (internal/child_process.js:899:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid @
16 verbose cwd C:\igsm-web
17 error Windows_NT 6.3.9600
18 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "dev"
19 error node v7.10.0
20 error npm  v4.2.0
21 error code ELIFECYCLE
22 error errno 3
23 error @ dev: `node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
23 error Exit status 3
24 error Failed at the @ dev script 'node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js'.
24 error Make sure you have the latest version of node.js and npm installed.
24 error If you do, this is most likely a problem with the  package,
24 error not with npm itself.
24 error Tell the author that this fails on your system:
24 error     node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
24 error You can get information on how to open an issue for this project with:
24 error     npm bugs
24 error Or if that isn't available, you can get their info via:
24 error     npm owner ls
24 error There is likely additional logging output above.
25 verbose exit [ 3, true ]


package.json

{
  "private": true,
  "scripts": {
    "dev": "node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "hot": "node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "production": "node node_modules/cross-env/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
  },
  "devDependencies": {
    "axios": "^0.15.2",
    "bootstrap-sass": "^3.3.7",
    "jquery": "^3.1.0",
    "laravel-mix": "^0.10.0",
    "lodash": "^4.16.2",
    "vue": "^2.3.3"
  },
  "dependencies": {
    "admin-lte": "~2.3.11",
    "bootstrap": "~3.3.7",
    "copy-webpack-plugin": "^4.0.1",
    "datatables.net": "~2.1.1",
    "datatables.net-bs": "~2.1.1",
    "datatables.net-buttons": "~1.2.4",
    "eonasdan-bootstrap-datetimepicker": "~4.17.43",
    "font-awesome": "~4.7",
    "fullcalendar": "~3.2.0",
    "jquery": "~1.11.2",
    "jquery-bridget": "^2.0.1",
    "jquery-floating-social-share": "~1.3",
    "masonry-layout": "^4.2.0",
    "moment": "~2.17.1",
    "morris.js": "~0.5",
    "nestable-fork": "~1.0",
    "raphael": "~2.2",
    "select2": "~4.0.2",
    "select2-bootstrap-theme": "~0.1.0-beta.4",
    "tinymce": "~4.2",
    "webfontloader": "~1.6"
  }
}

Solution attempt and fail

Solution 1 attempt with --max_old_space_size=2000000, 3000000 and 2048 and fail

Solution 2

install node-gyp globaly - fail

Solution 3

npm install --global windows-build-tools - fail

Someone know how can i fix it? thnks



via GabrielWaunous

How to use php & nodejs from separate containers

Let's say I have the following situation:

docker-compose.yml

version: '3'
services:
    web:
        build: .
        links:
            - apache
            - php
            - node
        depends_on:
            - apache
            - php
            - node
        volumes:
            - .:/var/www/html
    apache:
        image: httpd
    php:
        image: php
    node:
        image: node

and I also have a Dockerfile

FROM phusion/baseimage
RUN apt-get update
RUN apt-get install -yq git curl zip wget curl
RUN curl -s https://getcomposer.org/installer | php # error, no PHP exec found
RUN mv composer.phar /usr/local/bin/composer
RUN npm install -g bower gulp
COPY ./ /var/www/html
WORKDIR /var/www/html
RUN apt-get clean
RUN rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
CMD ["/sbin/my_init"]

Now my question is: how could I use PHP & Node, which are installed in separate containers, in this main app Dockerfile? Is that even possible, or do I need to manually install PHP & Node inside my Dockerfile?



via Borut

concat one file first in gulp

I build my project with gulp, into a file called all.js. In my workspace I have one file which I call modules.js. In this file I declare all of my namespaces. I would like gulp to concat this file first, at the top of all.js, and only then the rest of the js files. This way I don't have to worry about files order, and any namespace being not defined.

Here is what I have tried:

gulp.src("./src/main/modules.js")
    .pipe(concat("all.js"))
    .pipe(gulp.src(["./src/**/*.js", "!./src/main/modules.js"]))
    .pipe(concat("all.js"))
    .pipe(gulp.dest(dist));

But this way, modules.js is all that I see in all.js. the rest of the files are not being written at all.

How can I tell gulp to write modules.js into all.js first, and then add the rest of the js files after it?

Thank you!



via Yogev

im having a hard time understanding how the backend works with the frontend

so the frontend of web development is HTML CSS and JavaScript, html is what the browser renders to you so it could be readable to a human. CSS is to style the website, and javascript is for the behavior/interactive part of the frontend.

now where i seem to have a problem understanding is the backend part.

im taking a course and the programs that they are using are nodeJS and a database mongodb. are these two the only thing i need to learn? what exactly does nodeJS do?

sorry for my grammar



via Joatz

Does the Node.js debugger send SIGINT/SIGTERM when exiting with Ctrl-C?

While running tests, I'm running into a situation where a server I've started isn't closed when exiting the Node.js debugger, and it seems like this is causing the debugger to not stop listening on port 5858.

debug> 
(To exit, press ^C again or type .exit)
debug>
$

But then...

$ node debug test.js
< Error: listen EADDRINUSE :::5858
<     at Object.exports._errnoException (util.js:1022:11)
<     at exports._exceptionWithHostPort (util.js:1045:20)
<     at Agent.Server._listen2 (net.js:1259:14)
<     at listen (net.js:1295:10)
<     at net.js:1405:9
<     at _combinedTickCallback (internal/process/next_tick.js:77:11)
<     at process._tickCallback (internal/process/next_tick.js:98:9)
connecting to 127.0.0.1:5858 ... ok

When you have Node.js debugger running, and you hit Ctrl-C twice, what does it to do the process you were debugging? Does it send SIGTERM or SIGINT or SIGKILL or something else?

And why doesn't the debugger detach sometimes? Resulting in port 5858 still being in use.



via Ian Storm Taylor

Serving static files with Express

I've written a Node.js application using express. When I request /, I want to serve /public/app/index.html. This works. However, index.html includes two css and two js files, and the relative pathing breaks. The paths are set as such (in the HTML header) but when trying to obtain app.js and style.css, the (browser?) thinks to look at / because, of course, that's what is being served.

<link rel='stylesheet' href='/lib/lib.css'/>
<link rel='stylesheet' href='style.css'/>
<script type="application/javascript" src="/lib/lib.js"></script>
<script type="application/javascript" src="app.js"></script>

The reason why this is a problem to me that I use a build process for my HTML, and it was logical at the time to dump all built files into one folder (HTML, CSS, JS, images). That way a template HTML file could be used that always pointed to js and css within its own folder. I'm hoping I can avoid injecting scripts with relative pathing.

Folder structure

root/
├── public/
│   ├── lib/
|   |    ├── lib.js
|   |    └── lib.css
│   ├── app/
│   |    ├── index.html
│   |    ├── style.css
|   |    └── app.js
├── app.js
├── routes/
|     └── index.js

app.js

var app = express();
var server = app.listen(4100);
app.use(express.static(path.join(__dirname, 'public')));
// routes
var index = require('./routes/index');
app.use('/', index);

index.js

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

router.get('/', function(req, res, next) {
    var path = 'index.html';
    var options = {
        root : './public/app/'
    };
    res.sendFile(path, options, function(err){
        console.log(err)
    });
});

module.exports = router;



via jozenbasin

Checking if a string belongs to an array type value to a key in an object

Say I have an object called "groups", in it there are keys whose values are arrays:

let groups = {
    group1: ['A', 'B', 'C'],
    group2: ['X', 'Y', 'Z']
};
let item = 'B';

How would I go about finding out that the item is in fact in group1? (Note: There would be a lot of groups. I'm aware I could use a for loop to iterate over each of the keys in the object. But would there be a faster way?)



via Wright