Saturday 10 June 2017

'undefined' error when trying to access Firebase DB using JavaScript

This is what I have saved in DB enter image description here

This is my code which I used to try to access the data.

The goal is to get the value of the 1st id

var ref = db.ref("server/events/data");
ref.once("value", function(snapshot) { 

  var ids = snapshot.val();
  console.log(ids.id);

});

What am I missing ?



via Suhaib

Part of my js script not working in my ejs file

The "if" statement doesn't seem to work.

Here is my .ejs file:

<!DOCTYPE html>
<html>
<head>
        <title>causelist</title>
</head>
<body>
        <h1>Select the causes you want to back.</h1>
        <form action="/causelist" method="post">
                <% cause.forEach(function(cause){ %>
                <input type="checkbox" name="cause" value="<%= cause.CauseId %>" <% if (cause.CauseId===donate.CauseId1 || cause.CauseId===donate.CauseId2 || cause.CauseId===donate.CauseId3 || cause.CauseId===donate.CauseId4 || cause.CauseId===donate.CauseId5) { %> checked <% } %> > <%= cause.CauseName %> <br>
                <% }) %>
                <input type='submit'>
        </form>
</body>
</html>

Here is my app.get which renders the page and sends in values after retrieving from my MySQL DB:

app.get('/causelist', ensureAuthenticated, function(req,res){
connection.query("select * from DonateTo where UserId = "+ req.user.UserId, function(err,rows){
    if(err) console.log(err);
    var donate = rows;
    console.log("donate:"+ donate);
    connection.query("SELECT * FROM Causes",function(err,rows){
        var cause = rows;
        console.log("cause:"+ cause);
        res.render('causelist',{cause,donate});
        if(err)
        console.log(err);
    });
});
});

I don't understand what I'm missing.
Note: Except the if statement, the rest of the code works fine. i.e. data being retrieved from my DB is correct.



via Ishaan Shakunt

Express: receiving a router instance vs creating one on routes file

I'm grasping the basis of Express, and I'm wondering whether there's a difference or a standard choice with an objective reason for choosing one of these approaches when dealing with routes:

import { Router } from 'express';

const router = new Router();

router.get('/', (req, res) => res.send('hello world'));

export default router;

VS

export default function(router) {
    router.get('/', (req, res) => res.send('hello world'));
}

The first approach I took from the mern.io stack, and the second one from the krakenjs example.

At first glance (and having a OOP background) it looks like the second approach is designed for dependency injection; but since we're talking about javascript, I'm not sure the first one isn't. Also I'm not sure how testing is done, so maybe both cases are testables.

Any insights regarding which approach is considered the standard way and why would be appreciated.



via Christopher Francisco

Collect all redirected URL of Origin URL using NodeJS

I want to retrieve a list of urls that are redirected from Origin URL X and it may have many redirected URLs but i want all list of it.

For example:

http://www.example.com/origin-url

It will redirect to

http://www.example.com/first-redirect

Again it will redirect to

http://www.example.com/second-redicect

And finally it goes to this

http://www.example.com/final-url

So what i want is list of all this URLs using NodeJs or Express

 http://www.example.com/origin-url -->> http://www.example.com/first-redirect
 -->> http://www.example.com/second-redicect -->> http://www.example.com/final-url

Give me suggestion for this and which node module should i have to use to achieve this.

Thanks in advance.



via jay.jivani

Deploying a react native application which use node js

I have a react-native application which also uses node js server. I have no idea how to deploy it so that I can show demo on my phone. I don't want my phone to be connected to my laptop for demo. Any help is appreciated.



via Vijeet Vinod

pg-promise Chaining Queries for Task and Transactions

I have seen pg-promise tasks and tx to reuse same connection we can use

db.task(t => {
return t.one('SELECT id FROM Users WHERE name = $1', 'John')
    .then(user => {
        return t.any('SELECT * from Events WHERE userId = $1', user.id);
    });}).then(events => {// success
 }).catch(error => {
// error
});

But what if I have two different files and e.g. UsersModel.getUser(username) and EvenModel.getUserEvent(userId). Is there any way I can pass transaction or task objects.

thanks



via dev123

webpack - fs dependency not found

I did npm run dev. I get the following error. I installed fspackage using npmbut there is no js which I could include.

ERROR Failed to compile with 44 errors 10:40:35 AM

This dependency was not found:

  • fs in ./~/request/lib/har.js

To install it, you can run: npm install --save fs

What am I missing?



via Fahad Iqbal Ahmad Khan

PrintToPDF not working in headless Chrome 60

I'm trying to experiment with PDF printing via headless Chrome. This is the error I'm dealing with:

(node:6761) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: PrintToPDF is not implemented

Node.js package:

html-pdf-chrome

Dependencies:

✔ "chrome-remote-interface": "^0.23.1"  (v0.23.2 installed)   
✔ Chrome 59  (v60 beta installed)

Driver script:

const htmlPdf = require('html-pdf-chrome');
const html = '<p>Hello, world!</p>';
const options = {
    port: 9222, // port Chrome is listening on
};
htmlPdf.create(html, options).then((pdf) => pdf.toFile('test.pdf'));

Chrome 60 is installed and running in headless mode:

> google-chrome --version
Google Chrome 60.0.3112.24 beta

I've tracked down the code sections that calls Page.printToPDF which is where the error is raised:

const CDP = require("chrome-remote-interface");
...
const { Page } = client;
...
// https://chromedevtools.github.io/debugger-protocol-viewer/tot/Page/#method-printToPDF
const pdf = yield Page.printToPDF(options.printOptions);

I am able to perform other advertised functions like Page.captureScreenshot without fail.

How to get Page.printToPDF to perform as advertised?



via Drakes

Export default const with Typescript

I have this in a TS file:

exports.default = module.exports;

(This is to support both Node style and TS style imports.)

Is there a way to create the above line of code with pure TS instead of JS?

I tried this:

export default const = module.exports;

and that does not transpile.



via Alexander Mills

What configuration is needed for Webpack to do these things?

I've spent two day reading, and following tutorials. I have learned a lot, but I am stuck. I was able to accomplish things listed in tutorials but not combine them together.

Please write me a configuration file that would these things

  1. Compile Sass/Scss files into CSS file into public folder, not inline them anywhere.
  2. Transpile JSX/Es6 files into one file (I got this).
  3. Auto Refresh/Load page when Css OR Html changes.
  4. Auto Refresh/Load page when Javascript changes or React component etc.
  5. Plus Run via my own Nodejs Express server, not use webpack dev server, I want to avoid running multiple simultaneous processes. They make things hard.
  6. Whenever Css or js files changes, put hash into the file name for cache busting.
  7. ...Related to previous step, go through all templates and update urls everywhere they were generated.
  8. ...remove old hashed files.
  9. Minify, and generate Source Maps.

So Compile/Transpile Files, Live/Hot Reload, Hash Filenames, minify, and sourcemaps.

Right now I am thinking of abandoning Webpack, and only use it for transpiling and do everything in Gulpjs.

stuff in bold is where I had a lot of trouble as well. Existing Solutions include generating JSON file, and reading them per request (inefficent!), generating full html file and injecting them (breaks many flows plus cant modify script tag with special attributes if needed, they get written over).



via Muhammad Umer

Error 404 Node Js heroku app

I am trying to the replicate an example, just change ng-model name, and the url to communicate the client with the server, but that error show up.

Error

POST https://nuevohorario.herokuapp.com/enviarAsignatura 404 (Not Found)

Possibly unhandled rejection: {"data":"<h1>Not Found</h1>\n<h2></h2>\n<pre></pre>\n","status":404,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/enviarAsignatura","data":{"data":"calculo"},"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}},"statusText":"Not Found"}

Client -> Front - End

.controller('ctrl-asignatura',function($scope,sk,$http){

                        $scope.date= new Date();
                        $scope.data=[];
                        var vector = [];
                        $scope.m=function(){

                            //$scope.data.push($scope.informacion);
                            //console.log(vector)

                            $http.post('/enviarAsignatura', {data : $scope.asignatura}).then(function(response){
                                console.log(response);
                            })

                        }

                       sk.on('registrar',function(s){
                            alert(s);
                        });

Back End -> Node Js - Socket.IO

var express = require('express');
var router = express.Router();
var misocket = require('../routes/misocket');

/* GET users listing. */
router.post('/enviarAsignatura', function(req, res, next) {

    console.log(misocket);

    misocket.emit("registrar",req.body);
    console.log(req.body);
    res.status(200).json({
        message  : "send message"
    });

});

module.exports = router;



via Pedro Miguel Pimienta Morales

Alternative way to get response from a database in node js?

Im using MySql to store data from a node.js server

All the responses from a Query sent through node.js Conection.Query function is recieved through a callback function...

I was wondering if this is because is MySql...

is there any alternative for databases to get an answer immediately?

for example, this is the standard way im doing it now.

Self.Conection.query(Query, function(err, result) {
    //handling result here
    });

Is there any way to achieve the next example?

var response=Query("select * from table");



via AlexAdagio

Cheerio Error: ReferenceError: $ is not defined

I am trying to iterate over table rows.But when I use $ to find an element from inside the .each function,it raises the above error.

var $ = cheerio.load(html);
.....
var headers = $('[id*=tableone] tbody tr')

 headers.each(function(header_index, header_elem){
    console.log($(header_elem))                         => exception here
   })



via Jaswinder

How to update a JSON file using NodeJs? The data I want to post to the file is in my jquery program logic

How can I update my JSON file (can be found in the same local server as app.js containing all my program logic) using NodeJS? Should I put all of my program logic within nodeJS instead of having it in an external js file? If that's not necessary, how can I tell NodeJS to take data from my program logic and update the json file using NodeJS?

Any help will be appreciated



via Lean Junio

Passport JWT is always returning 401 unauthorized when using OpenID Connect ID Token

I am following this tutorial to enable jwt authentication in my express API. https://jonathanmh.com/express-passport-json-web-token-jwt-authentication-beginners/

If I use a standard username/password authentication, I am able to use JwtStrategy to authenticate the JWT Token that I receive in the request header. jwt.sign() happens on the user id and secret. All of this works fine.

When I try to modify this code to verify the id_token (JWT Token signed using RS256) from OpenID Connect, then I get 401 Unauthorized no matter what. I tried to debug in the JwtStrategy method and it looks like the request doesn't even go inside that function. This id_token appears to be a lot longer than the one signed with HS256 algorithm.

A simple passport.authenticate call app.get('/callback', passport.authenticate('jwt', { session: false }), function(req, res, next) { });

Can someone please explain why it doesn't even recognise my token?



via mayurc

Pass array to async library eachSeries - expects 'Dictionary<{}>'

I have the following TypeScript code:

const allDescribeBlocks: Array<ITestSuite> = suman.allDescribeBlocks;

async.eachSeries(allDescribeBlocks, function (block: ITestSuite, cb: Function) {

//....

}, cb);

this will transpile with warnings:

Argument of type ITestSuite[] is not assignable to parameter of type Dictionary<{}>. Index signature is missing in ITestSuite[].

How to fix?

Here is the exact warning:enter image description here



via Alexander Mills

I can't get data from my Json file which contains small json files

My problem is I have Json file of small json file creadted with node js I couldn't consume my json from that link and i tried to test my json file in some website like Json formatter there is this error : Multiple JSON root elements . when i put only one json in json formatter it become right but like this example 2 json it it wrong this is the example of my json of 2 json ,

{"@timestamp":"2017-06-11T00:28:24.112Z","type_instance":"interrupt","plugin":"cpu","logdate":"2017-06-11T00:28:24.112Z","host":"node-2","@version":"1","collectd_type":"percent","value":0} {"@timestamp":"2017-06-11T00:28:24.112Z","type_instance":"softirq","plugin":"cpu","logdate":"2017-06-11T00:28:24.112Z","host":"node-2","@version":"1","collectd_type":"percent","value":0}



via Aziz Sakly

How to assert the type of mouse cursor before and onHover on an element in Selenium Webdriver ?

The type of cursor before is 'pointer'. And while onHover the cursor changes its type to 'arrow'. Need to assert that the cursor before and after has the correct types.



via T Gurung

Do i need Promise.promisifyAll() in every module file?

If i need fs in multiple files with Promise (Bluebird), should i call every time Promise.promisifyAll(require('fs')) ? Or would it be better with a small module with

module.exports = Promise.promisifyAll(require('fs'))

and only import that module?

If i get it right, my first choice will every time promisfy the fs module and the second will only link to the same module, which is only one time promisfyed. Or will be my first choice doing the same like my second?



via Defkil

How to get specific data from large json object into Jade mixin

This is the json from my sever:

data = {"id":393, "state":"mississippi", "lat":null, "lng":null, "title":"someTitle", "country":null};

I then pass that through a Jade temple like so: res.render('editUpload', {fromServer:data});

Then in my Jade template I have this:

var data = !{fromServer};
console.log(data.address);

Which correctly prints mississippi

However, I'm trying to get my mixins to use that data

Mixin:

mixin textBoxMixin(name, label, value)
    div(style="display:flex; width:100%;")
        span.label #{label}
        input(type="text", name="#{name}", value="#{value}")

Then I use that like this:

+textBoxMixin("title", "Title", fromServer)

which fills in the text box with the entire json "{"id":393, "state":"mississippi", "lat":null, "lng":null, "title":"someTitle", "country":null}" so I go and try this:

+textBoxMixin("title", "Title", fromServer.title)

it prints "undefined".

How do I get this mixin to accept what should just be fromServer.title?

I've tried JSON.stringify(fromServer), data.address (which obviously doesn't work because data is undefined during the rendering of the page). I know that I could go back to my server and parse out all the json there and pass each item as an individual item, but that would be a giant pain since my json is actually much larger than what I've posted here.



via Glen Pierce

AWS DynamoDB ConditionExpression not working

I'm using the javascript/nodejs AWS SDK DynamoDB Document client. My condition expression isn't working properly. I'm wanting to prevent adding emails to the "emails" list if that email is listed in the "blockedEmails" list. This isn't working however, and DynamoDB just allows me to add the email even with the condition expression.

Here's the code:

  var index = {
    TableName: getTableName(event),
    Key: {
      accountId: accountId
    },
    UpdateExpression: "SET #emails = list_append(if_not_exists(#emails, :empty_list), :email)",
    ConditionExpression: "(attribute_not_exists(#emails) or not(contains(:emailIndividual, #emails))) and (attribute_not_exists(#blockedEmails) or not(contains(:emailIndividual, #blockedEmails)))",
    ExpressionAttributeNames: {
      "#emails": "emails",
      "#blockedEmails": "blockedEmails"
    },
    ExpressionAttributeValues: {
      ":email": [email],
      ":emailIndividual": email,
      ":empty_list": []
    }
  };

  console.log(JSON.stringify(index));

  dynamodb.update(index, function(err) {
    if(err) {
      reject(err);
    } else {
      resolve();
    }
  });

Here's what the object looks like with values:

{
    "TableName": "dev-netcountable-accounts",
    "Key": {
        "accountId": "ABCD-1234"
    },
    "UpdateExpression": "SET #emails = list_append(if_not_exists(#emails, :empty_list), :email)",
    "ConditionExpression": "(attribute_not_exists(#emails) or not(contains(:emailIndividual, #emails))) and (attribute_not_exists(#blockedEmails) or not(contains(:emailIndividual, #blockedEmails)))",
    "ExpressionAttributeNames": {
        "#emails": "emails",
        "#blockedEmails": "blockedEmails"
    },
    "ExpressionAttributeValues": {
        ":email": [
            "bob@nowhere.com"
        ],
        ":emailIndividual": "bob@nowhere.com",
        ":empty_list": []
    }
}

Here's what the record currently looks like in DynamoDB

{
  "accountId": "ABCD-1234",
  "blockedEmails": [
    "bob@nowhere.com"
  ],
  "emails": [
    "success@simulator.amazonses.com"
  ]
}



via CamHart

ELI5 Including an npm package

I understand including packages in an app using a framework such as Angular 2, but I'm lost when it comes to including a package into static, fully custom websites. For example:

  • I create the package.json file, great.
  • I install and --save the package into the package.json file, great.

Now what? For Javascript packages it typically says to write the require(''); line or for CSS packages it might say to include the @import('');, but where?

Typically I'm just running a static site with a /css and /js folder. Do I insert the require() or import() in the main JS or CSS file? If so, how does it know to read into the /node_modules folder?

Thanks in advance.



via Joe Berthelot

How do i format mysql query to utilize async/promsies?

I'm trying to make a simple query on my database with 2 parameters, and I'm having trouble trying to reformat this code using Promises/Async to avoid callback hell. Here is the code:

module.exports = {
  getDailyRaw: function(school, meal, callback) {
     var sql = "SELECT * FROM daily WHERE school = ? AND meal = ?";
     pool.getConnection(function(err, conn) {
         if(err) { console.log(err); callback(true); return; }
         conn.query(sql, [school, meal], function(err, results) {
             conn.release();
             if(err) { console.log(err); callback(true); return; }
             callback(false, school, results);
         })
     })
  }, ....

I've been constantly trying to look up tutorials on fixing this issue, but haven't been able to implement/understand them properly.



via Kevin Lee

io.emit fails to emit to all clients

I am trying to implement a "leave game" feature in a simple socket.io game and I cannot figure out why io.emit notifies only the socket of the client leaving the game. Here is my socket.js code:

io.on("connection", sock => {

    sock.on('joinGame', name => {
       inc++
       if(name === 'guest') name = name + inc.toString()
       addToGame(inc, name) // adds player to a new Map()
       io.emit('joinedGame', name)   
    })

    sock.on('findPlayersInGame', () => {
       getAllPlayersInGame(io, threeOrMore)
     // check to see if the client is notified when a new user joins
       io.emit('newPlayerJoined', 'new player joined')
    })

    sock.on('leaveGame', name => {
       io.emit('leftGame', uniquePlayers)    
    })

On the client, I am handling the socket communication along with my state management in a MobX store. Here is my GameStore.js code:

export class GameStore {
constructor(aGame) {
    extendObservable(this, {
        players: [],
        game: aGame,
        menuVisibility: true,
        play: action((id, username) => {
            this.menuVisibility = false
            username === undefined ? this.game.setName("guest") : this.game.setName(username)

            // join game with given username
            sock.emit('joinGame', this.game.playerName)

            // after joining, if the username is 'guest' change name to unique guest name provided by server
            sock.on('joinedGame', name => {
                if(this.game.playerName === 'guest') this.game.setName(name)
                console.log(this.game.playerName + " joined the game")
            })
            // populate player list with all players in game room
            this.loadPlayers()
        }),
        quitGame: action(() => {
            //this.menuVisibility = true
            sock.emit('leaveGame', this.game.playerName)
            sock.on('leftGame', players => { // this should be logged to all clients
                console.log('updated player list', players)
                this.players = players
            })
        }),
        loadPlayers: action(() => {
            sock.emit('findPlayersInGame', this.game.playerName)
            sock.on('loadPlayers', players => {
                console.log('loading players...')
                this.players = players
            })
            sock.on('newPlayerJoined', player => {
                console.log(player)
            })
        })   
    })
  }
}

When I dispatch the quitGame action, the socket only emits to the client that is leaving the game. I need to update the player list in my store after someone leaves the game, but I cannot figure out why the other clients are not getting the message that someone left the game. io.emit seems to be working fine when a player joins a game.



via Mahmud Adam

AWS ElasticBeanstalk NodeJS - not recognizing .css file

Wondering if anyone could help me? I have had a website running on Elastic Beanstalk for quite sometime. The css file was working just fine. I have not changed the structure of the app and it works just fine on my local machine. However a few weeks ago I uploaded a new version and it will not recognize my css file (my formatting isn't working). I uploaded it again the night before last and again it still doesn't recognize it. (Just to be clear I have not changed the structure and it works on my local machine). I know this is a bit tricky, but maybe someone has had this happen and can explain.



via SharonS

Swagger error: Relative paths to the individual endpoints

I have created a nodejs 'Hello World' project and I was trying to reorganize the swagger.yaml taking the paths out of the main yaml file into a sepparate paths.yam file:

This is my api/swagger/swagger.yaml:

swagger: "2.0"
info:
  version: "0.0.1"
  title: Hello World App
# during dev, should point to your local machine
host: localhost:10010
# basePath prefixes all resource paths
basePath: /
#
schemes:
  # tip: remove http to make production-grade
  - http
  - https
# format of bodies a client can send (Content-Type)
consumes:
  - application/json
# format of the responses to the client (Accepts)
produces:
  - application/json
paths:
  $ref: './paths.yaml'
  /swagger:
    x-swagger-pipe: swagger_raw
# complex objects have schema definitions
definitions:
  HelloWorldResponse:
    required:
      - message
    properties:
      message:
        type: string
  ErrorResponse:
    required:
      - message
    properties:
      message:
        type: string

and this is the api/swagger/paths.yaml that I'm referencing to:

/hello:
  # binds a127 app logic to a route
  x-swagger-router-controller: hello_world
  get:
    description: Returns 'Hello' to the caller
    # used as the method name of the controller
    operationId: hello
    parameters:
      - name: name
        in: query
        description: The name of the person to whom to say hello
        required: false
        type: string
    responses:
      "200":
        description: Success
        schema:
          # a pointer to a definition
          $ref: "#/definitions/HelloWorldResponse"
      # responses may fall through to errors
      default:
        description: Error
        schema:
          $ref: "#/definitions/ErrorResponse"

I get the following Swagger error:

Relative paths to the individual endpoints. They must be relative to the 'basePath'.

Reference could not be resolved: ./paths.yaml

Both files 'swagger.yaml' and 'paths.yaml' are placed in the same directory 'api/swagger/'. I've tried to reference paths.yaml in different ways:

paths:
  $ref: 'paths.yaml'

or

paths:
  $ref: './api/swagger/paths.yaml'

But I get the same error. Is it possible to reference the paths in a sepparate yaml file?



via rodrunner

Docker(compose) installing nodejs broke npm

I need to use a container with nginx and nodejs, so I take the nginx container and install the node:

FROM nginx

ENV DEBIAN_FRONTEND noninteractive

WORKDIR /usr/src/app
VOLUME /usr/src/app


RUN apt-get update && \
  apt-get install -y apt-utils && \
  apt-get install -y --no-install-recommends curl sudo wget nano && \
  curl -sL https://deb.nodesource.com/setup_4.x | bash - && \
  apt-get install -y nodejs git build-essential && \
  whereis npm
  npm install grunt grunt-cli bower -g && \

whereis returnme nothing npm:, and npm install... crash the build proccess. so Where ir my mistake, is there a bug or anything? btw I'm using latest docker-compose and Docker version 17.03.1-ce, build c6d412e



via Daniel Fox

Twilio nodejs client specify PageSize query parameter

Per the doc, one should be able to specify the PageSize parameter when doing a GET list of resources

https://www.twilio.com/docs/api/rest/response#response-formats-list-filters

How do you do this using NodeJS client? The only available parameters to be passed in to /Accounts/[AccountSid]/Messages/[MessageSid] are (from/to/dateSent)



via timpham

Update function mongoose

router.put('/:student_id', function (req, res, next) {

Student.findOneAndUpdate(req.params.student_id, req.body, function (error) {

    if (error) res.status(500).json({
        success: false,
        error: error
    });
    res.status(200).json({
        success: true,
        data: student
    });
});

});



via Bilel Harabi

Modify a JSON object between two files

I am developing a nodejs project and stuck at this problem. I have a empty JSON object in one file and will update this object value in secondfile.

jsonFile.js

var jsonObj = {



    first: []

    ,
    second: []


    ,
    third: [],
};


exports.jsonObj=jsonObj;

pushdata.js

 var obj= require('./jsonFile.js');
                // i'll retrieve data from file and push into the obj...
for the sake of simplicity im not writing data fetching code..

                ojb.jsonObj.first.push("user1");

How can I update this json object in pushdata.js file in such a way that it also updates/change the json object in jsonFile.js



via Alturistic

AWS codedeploythrowing error missing script: stop

This the Error

Error CodeScriptFailed
Script Namescripts/stop.sh
MessageScript at specified location: scripts/stop.sh run as user root failed with exit code 1
Log TailLifecycleEvent - ApplicationStop
Script - scripts/stop.sh
[stderr]npm ERR! Linux 3.10.42-52.145.amzn1.x86_64
[stderr]npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "stop"
[stderr]npm ERR! node v4.8.3
[stderr]npm ERR! npm  v2.15.11
[stderr]
[stderr]npm ERR! missing script: stop
[stderr]npm ERR! 
[stderr]npm ERR! If you need help, you may report this error at:
[stderr]npm ERR!     <https://github.com/npm/npm/issues>
[stderr]
[stderr]npm ERR! Please include the following file with any support request:
[stderr]npm ERR!     /var/nodejs/CodeDeployDemo/npm-debug.log

This is my appspec.yml

version 0.0
os: linux
files:
  - source: /
    destination: /var/nodejs/CodeDeployDemo/

hooks:
  BeforeInstall:
    - location: scripts/install.sh
      timeout: 300
      runas: root
  AfterInstall:
    - location: scripts/post_install.sh
      timeout: 600
      runas: root
  ApplicationStart:
    - location: scripts/run.sh
      timeout: 120
      runas: root
  ApplicationStop:
    - location: scripts/stop.sh
      timeout: 120
      runas: root
  ValidateService:
    - location: scripts/validate.sh
      timeout: 60
      runas: root

Thanks



via Adiii

All callbacks are executing at the same time but why?

I'm currently wrapping an executable I've made with NodeJS. The executable can save strings for use in other processes within the executable. Each time the executable 'saves' a string it sends a pointer back to the server via stdout. The NodeJS server saves strings by sending them to stdin of the executable.

Originally I was writing code like this:

CLRProcess.stdout.once('data',function(strptr){
    CLRProcess.stdout.once('data', function(str){
         console.log(str.toString())
    })
    CLRProcess.stdin.write("StringReturn " + strptr.toString())
})
CLRProcess.stdin.write("StringInject __CrLf__ Mary had a__CrLf__little lamb.")

The above code injects a string

Mary had a
little lamb.

receives a pointer to the string, and then requests the string in the next step, by sending the pointer back to the host application.

To make coding algorithms easier I wanted a system like this:

strPtr = Exec("StringInject __CrLf__ Mary had a__CrLf__little lamb.")
str = Exec("StringReturn " + strPtr)
// do stuff with str

This is the code I made:

class Pointer {
    constructor(){
        this.value = undefined
        this.type = "ptr"
    }
}


class CLR_Events extends Array {
    constructor(CLR){
        super()
        this.CLR = CLR
    }
    runAll(){
        if(this.length>0){
            //Contribution by le_m: https://stackoverflow.com/a/44447739/6302131. See Contrib#1
            this.shift().run(this.runAll.bind(this))
        }
    }
    new(cmd,args,ret){
        var requireRun = !(this.length>0)   //If events array is initially empty, a run is required
        var e = new CLR_Event(cmd,args,ret,this.CLR)
        this.push(e)
        if(requireRun){
            this.runAll()
        }
    }
}

class CLR_Event {
    constructor(cmd,args,ret,CLR){
        this.command = cmd;
        this.args = args
        this.CLR = CLR
        this.proc = CLR.CLRProcess;
        this.ptr = ret
    }

    run(callback){
        //Implementing event to execute callback after some other events have been created.
        if(this.command == "Finally"){
            this.args[0]()
            console.log("Running Finally")
            return callback(null)
        }

        //Implementation for all CLR events.
        var thisEvent = this
        this.proc.stdout.once('data',function(data){
            this.read()
            data = JSON.parse(data.toString())
            thisEvent.ptr.value = data
            callback(data);
        })
        this.proc.stdin.write(this.command + " " + this._getArgValues(this.args).join(" ") + "\n");
    }
    _getArgValues(args){
        var newArgs = []
        this.args.forEach(
            function(arg){
                if(arg.type=='ptr'){
                    if(typeof arg.value == "object"){
                        newArgs.push(JSON.stringify(arg.value))
                    } else {
                        newArgs.push(arg.value)
                    }
                } else if(typeof arg == "object"){
                    newArgs.push(JSON.stringify(arg))
                } else {
                    newArgs.push(arg)
                }
            }
        )
        return newArgs  
    }
}

var CLR = {}
CLR.CLRProcess = require('child_process').spawn('DynaCLR.exe')
CLR.CLRProcess.stdout.once('data',function(data){
    if(data!="Ready for input."){
        CLR.CLRProcess.kill()
        CLR = undefined
        throw new Error("Cannot create CLR process")
    } else {
        console.log('CLR is ready for input...')
    }
})
CLR.Events = new CLR_Events(CLR)

//UDFs

CLR.StringInject = function(str,CrLf="__CLR-CrLf__"){
    var ptr = new Pointer
    this.Events.new("StringInject",[CrLf,str.replace(/\n/g,CrLf)],ptr) //Note CLR.exe requires arguments to be the other way round -- easier command line passing
    return ptr
}
CLR.StringReturn = function(ptr){
    var sRet = new Pointer
    this.Events.new("StringReturn",[ptr],sRet)
    return sRet
}

CLR.Finally = function(callback){
    this.Events.new("Finally",[callback])
}

I intended this to do the following:

  1. Functions StringInject, StringReturn and Finally create events and append them to the Events array.
  2. The runAll() function of the Events object, removes the first 'event' from its array and runs the run() function of the array, passing itself as a callback.
  3. The run functions writes to stdin of the executable, waits for a response in stdout, appends the data to the passed in pointer and then executes the runAll() function passed to it.

This is what I don't understand... When executing the multiple string injections:

S_ptr_1 = CLR.StringInject("Hello world!")
S_ptr_2 = CLR.StringInject("Hello world!__CLR-CrLf__My name is Sancarn!")
S_ptr_3 = CLR.StringInject("Mary had a little lamb;And it's name was Doug!",";")

I get the following data:

S_ptr_1 = {value:123,type:'ptr'}
S_ptr_2 = {value:123,type:'ptr'}
S_ptr_3 = {value:123,type:'ptr'}

Where as the data should be:

S_ptr_1 = {value:1,type:'ptr'}
S_ptr_2 = {value:2,type:'ptr'}
S_ptr_3 = {value:3,type:'ptr'}

The only scenario I can think this would happen is if, in pseudocode, the following happenned:

CLRProcess.stdin.write("StringInject Val1")
CLRProcess.stdin.write("StringInject Val2")
CLRProcess.stdin.write("StringInject Val3")
CLRProcess.stdout.once('data') ==> S_ptr_1
CLRProcess.stdout.once('data') ==> S_ptr_2
CLRProcess.stdout.once('data') ==> S_ptr_3

But why? Am I overlooking something or is there something fundamentally wrong with this algorithm?



via Sancarn

Best way to pass process.env.ENV to my react app?

My react app needs to know if the ENV is production or development, and I set it in my .env file on my express server perfectly, but I don't know how to inject that successfully into the client code which needs to know the ENV to determine if the link is localhost or mysite.com



via joe

Run script on nodeJS server under a memory limit

I have a nodejs server deployed to heroku. It doesn't have much load except once a day, when it parses quite a big piece of data (~20mb JSON file).

It takes about 20 seconds on macbook pro.

Heroku starts complaining about memory limit Error R14 (Memory quota exceeded) and eventually terminates the process.

How do i make the script to run under specified memory limit? It's okay if it will take few minutes instead of 20 seconds.



via stkvtflw

index.html not invoking javascript file

I'm making a simple client/server connection via node.js modules and a simple HTML page.

the html page is this:

<script type="text/javascript" src="index.js"></script>

Where the index.js file in the same directory is this:

alert("hello!");

This works fine when I manually click on the html page, but when I invoke it using my app.js:

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

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/web/index.html');
});
app.use('/web', express.static(__dirname + '/web'));
server.listen(2000); 

console.log('Started Server!');

by calling

node app.js

it does not show the alert when the HTML page loads. I just installed node.js and installed the node express dependencies in this app after I called "node init" on the project.



via Kevin Hu

nodejs logger module wrong context

I have a simple nodejs logger module to print 'time, context and message'

module.exports = {

  init: (c) => {

    const config = c || {};
    const context = config.context || 'ROOT';

    console.log('test', c, config);

    return {

      d: (message) => {
        console.log(`${new Date()} [${context}] Debug - ${message}`);
      },

      i: (message) => {
        console.log(`${new Date()} [${context}] Info  - ${message}`);
      },

      w: (message) => {
        console.log(`${new Date()} [${context}] Warn  - ${message}`);
      },

      e: (message) => {
        console.error(`${new Date()} [${context}] Error - ${message}`);
      }

    }

  }

}

Now I require this module from other modules inside my app.

const logger = require('./logger').init('Database'); or const logger = require('./logger').init('WebSocket');

But for some reason from every logging on my console, the context is 'ROOT' but console.log('test', c, config); is called multiple times with the right c and config.

I know that modules are like singletons in one app scope but it is called... Any Ideas?



via Pascal

How to include "redux-file-upload" in my React App

I have found this redux-file-upload called upload.js

import { FileUpload } from 'redux-file-upload'

<FileUpload

allowedFileTypes={['jpg', 'pdf']}
  data=
  dropzoneId="fileUpload"
  url="./uploads/"
>
  <button>
    Click or drag here
  </button>
</FileUpload>

and I want to use it in React. this file is called Tab5.js :

import React from 'react';
import './../css/bootstrap.css';
import './../css/styles.css';
import Modale from './modalProces';


class Tab5 extends React.Component {
    render () {
        return (
            <div>
                <FileUpload />
            </div>
        );
    }
}
 export default Tab5;

but whenever I run it, Tab5 doesn't show up.

I already installed:
-npm install --save redux
-npm install --save react-redux
-npm install --save-dev redux-devtools
-npm install --save redux-file-upload

Am I missing any imports? Am I doing the whole thing wrong?
I'm not used to coding in React, but I'm forced to do this part.
I just need the file upload to work, where it uploads a file into the uploads folder.

Please Help me.



via sventastic

Handlebars syntax

currently trying to get into handlebars. Firstly does anyone have any suggestions on where I should go to learn the handlebars syntax. Secondly could anyone help me with how to translate this into handlebars.

<li>
        <a class="dropdown-toggle" data-toggle="dropdown" href="#"> Categories <span class="caret"></span></a>
        <ul class="dropdown-menu">
          <% for (var i = 0; i < categories.length; i++) { %>
            <li><a href="/products/<%= categories[i]._id %>"> <%= categories[i].name %></a></li>
          <% } %>
        </ul>
      </li>



via Troy

passport-local error 401: Unauthorized

I'm trying to get passport-local to work in my node.js koa2 project. But I only got as far as a 401 "Unauthorized" error, when I try to register a new user..

Mongoose MongoDB connection seems to work (no error, only a warning):

Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will on
ly allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClie
nt.connect with auth credentials.

index.js

require('console-stamp')(console, '[HH:MM:ss.l]')

const cfg = require('./config/config')
const koa = require('koa')
const mount = require('koa-mount')
const static = require('koa-static')
// const Pug = require('koa-pug') //not in this code
const session = require('koa-session')
const mongoose = require('mongoose')
const passport = require('koa-passport')

const app = module.exports = new koa()

mongoose.connect('mongodb://' + cfg.user + ':' + cfg.pass + '@' + cfg.host + '/' + cfg.database + '?authSource=admin')

require('./config/passport')(passport)

app
  .use(session({}, app))
  .use(passport.initialize())
  .use(passport.session())
  .use(mount('/assets', static('./src/views/' + cfg.view)))
  .use(require('./src/routes').routes())
  .use(require('./src/routes/authentication').routes())
  //.use(require('./src/routes/admin').routes())
  .listen(cfg.app_port, () => {
    console.info(cfg.app_name + ' is running on ' + cfg.app_host + ':' + cfg.app_port)
  })
  .on('error', function (err) {
    console.info(err.stack)
  })

src/routes/authentication.js

const cfg = require('../../config/config')
const locals = require('../../config/locals/' + cfg.locals)
const app = require('../../')
const Router = require('koa-router')
const passport = require('koa-passport')

const router = module.exports = new Router()

router
  .get('/' + locals.signup_adress, async (ctx, next) => {
    await ctx.render('signup', {
      title: cfg.app_name
    })
  })
  .post('/' + locals.signup_adress, async (ctx, next) => {
    return passport.authenticate('local-signup', async (err, user, info, status) => {
      if (user === false) {
        ctx.body = { success: false }
        return ctx.throw(401)
      } else {
        ctx.body = { success: true }
        return ctx.login(user)
      }
    })(ctx, next)
  })

config/passport.js

const localStrategy = require('passport-local').Strategy
const user = require('../src/models/user')

module.exports = function (passport) {
  passport.serializeUser(function (user, done) {
    done(null, user.id)
  })

  passport.deserializeUser(function (id, done) {
    user.findById(id, function (err, user) {
      done(err, user)
    })
  })

  passport.use('local-signup', new localStrategy({
    usernameField: 'username',
    passwordField: 'password',
    passReqToCallback: true
  },
  function (ctx, username, password, done) {
    process.nextTick(function () {
      user.findOne({'local.username': username}, function (err, user) {
        if (err) return done(err)
        if (user) return done(null, false, ctx.flash('signupMessage', 'That username is already taken.'))
        else {
          const newUser = new user()

          newUser.local.username = username;
          newUser.local.email = email;
          newUser.local.password = newUser.generateHash(password);

          newUser.save(function (err) {
            if (err) throw err
            return done(null, newUser)
          });
        }
    })
    })
  }))

  passport.use('local-login', new localStrategy({
    usernameField: 'username',
    passwordField: 'password',
    passReqToCallback: true
  },
  function (ctx, username, password, done) {
    user.findOne({'local.username': username}, function (err, user) {
      if (err) return done(err)
      if (!user) return done(null, false, ctx.flash('loginMessage', 'No user found.'))
      if (!user.validPassword(password)) return done(null, false, ctx.flash('loginMessage', 'Oops! Wrong password.'))
      return done(null, user)
    })
  }))
}



via Dima Kiltau

Mean application on azure webapp

i've an application Mean that will deployed on Azure in a continous delivery. We have define on VSTS a build script that build typescript to JS file, clean up unuseful files, a gulp task that zip files and finally copy zip files on drop folder.

After on release level we will have a script for IT environment, staging environment.

Actually we have an Azure Web App Deployment task, it takes the zip files and decompress the files rightly.

But if i let the node-modules folder it takes more that 2 hours ...

i search a solution to launch an 'npm instal' after this task.

I know that's possible to go to Kudu and aunch the npm install.

I've tested solution with a deploy.sh (see on the net) but task not launch automatically like i see.

I've try to launch a power shell script but it's failed ...

I've the feeling that's not possibl except manual intervention via kudu or other ..

In our company we need a full automation of the deployment.

I hope someone can help me ... i'm really blocked.

Thanks in advance



via Mattious

How do you use SetAlert with the Node.js Alex Skill SDK?

I am a ASK n00b and I want to create a skill, that when activated will send messages to the user on a schedule. Later I want to pause/resume that schedule. I am currently hacking the Node.js fact example to learn the ropes, but could use some veteran knowledge and help.

Examples are the preferable response.



via user3791832

routes in nodejs/express get called twice

im working in an existing project, and i have a problem driving me insane:

the routes are getting called twice or maybe even more, this happens when any route called take too long to respond

i think the problem is in this file, a dynamic routing attempt

            var express = require('express');
            var recaptcha = require('express-recaptcha');
            //Site key, Secret key
            recaptcha.init('6LendhYTAAAAAMILyseJMvu8ts2c9AYmQgU-T8si', '6LendhYTAAAAABOQ96N8rb7ASIJtKqBfprl-NiiM');
            /**
             * Routes middleware
             * Check all requests
             */
            module.exports = function(app, passport, memoryCache) {

              var router = express.Router();
              var config = require('app/config/settings.js');

              router.use(function(req, res, next) {

                console.log("touch");
                console.log(req.url);
                /**
                 * Make visible req / res on template layout
                 */
                res.locals.req = req;
                res.locals.res = res;
                /**
                 * Url filter
                 */
                var aryUrl = req.path.split('/').filter(Boolean);

                try {

                  var root = '';
                  var controller = '';
                  var controllerPrototype = '';
                  var module = '';
                  var method = '';
                  var url = '';
                  var itemId = '';
                  var privacity = '';
                  var session = '';

                  switch (req.originalMethod) {
                    case 'GET':
                      method = 'get';
                      break;
                    case 'POST':
                      method = 'post';
                      break;
                    case 'PUT':
                      method = 'put';
                      break;
                    case 'DELETE':
                      method = 'delete';
                      break;
                  }

                  if (aryUrl.length == 0) {
                    root = '/';
                  } else {
                    root = aryUrl[0];
                  }

                  switch (root) {
                    case '/':
                      privacity = 'private';
                      session = 'General';
                      module = 'app/controllers/indexController';
                      controller = 'index';
                      controllerPrototype = 'root';
                      url = '/';

                      break;
                    case 'index':
                      privacity = 'private';
                      session = 'General';
                      module = 'app/controllers/indexController';
                      controller = 'index';
                      controllerPrototype = aryUrl[1];
                      url = '/index/' + aryUrl[1];

                      break;
                    case 'evaluaciones':
                      privacity = 'private';
                      session = 'PortalEval';
                      module = 'app/controllers/view-private/portalEvaluacionController';
                      controller = 'portalEvaluacion';
                      controllerPrototype = 'view';
                      url = '/evaluaciones';

                      if (aryUrl.length == 2) {
                          if (aryUrl[1] === 'antesdelcurso' || aryUrl[1] === 'despuesdelcurso') {
                              url = url + '/' + aryUrl[1];
                          } else {
                              controller = '';
                          }
                      }
                      break;
                    case 'relatores':
                        privacity = 'private';
                        session = 'RelatorEval';
                        module = 'app/controllers/portalRelatoresIndexController';
                        controller = 'portalRelatores';
                        controllerPrototype = 'view';
                        url = '/relatores';
                        break;
                    case 'api-pc':
                      privacity = 'public';
                      session = (req.user)? req.user.tipoSession : '';
                      var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
                        return chr.toUpperCase();
                      });
                      ctrl = 'api' + ctrl.charAt(0).toUpperCase() + ctrl.slice(1);

                      module = 'app/controllers/api-public/' + ctrl + 'Controller';
                      controller = ctrl;

                      if (aryUrl.length == 4) {
                        itemId = '/:id';
                      }

                      controllerPrototype = aryUrl[2];

                      url = '/api-pc/' + aryUrl[1] + '/' + aryUrl[2] + itemId;

                      break;
                    case 'api-pt':
                      privacity = 'private';
                      session = (req.user)? req.user.tipoSession : '';
                      var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
                        return chr.toUpperCase();
                      });
                      ctrl = 'api' + ctrl.charAt(0).toUpperCase() + ctrl.slice(1);

                      module = 'app/controllers/api-private/' + ctrl + 'Controller';
                      controller = ctrl;

                      if (aryUrl.length == 4) {
                        itemId = '/:id';
                      }

                      controllerPrototype = aryUrl[2];

                      url = '/api-pt/' + aryUrl[1] + '/' + aryUrl[2] + itemId;

                      break;
                    case 'view-pc':
                      privacity = 'public';
                      session = (req.user)? req.user.tipoSession : '';
                      var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
                        return chr.toUpperCase();
                      });

                      module = 'app/controllers/view-public/' + ctrl + 'Controller';
                      controller = ctrl;

                      if (aryUrl.length == 4) {
                        itemId = '/:id';
                      }

                      controllerPrototype = aryUrl[2];

                      url = '/view-pc/' + aryUrl[1] + '/' + aryUrl[2] + itemId;

                      break;
                    case 'view-pt':
                      privacity = 'private';
                      session = (req.user)? req.user.tipoSession : '';
                      var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) {
                        return chr.toUpperCase();
                      });

                      module = 'app/controllers/view-private/' + ctrl + 'Controller';
                      controller = ctrl;

                      if (aryUrl.length == 4) {
                        itemId = '/:id';
                      }

                      controllerPrototype = aryUrl[2];

                      url = '/view-pt/' + aryUrl[1] + '/' + aryUrl[2] + itemId;

                      break;
                    case 'auth':
                      /**
                      * Local Login
                      */
                      var successGetLog = function(req, res) {
                        res.render('login/get.html', {
                          layout: 'layout/auth.html',
                          entorno: config.config_entorno.empresa,
                          message: req.flash('loginMessage'),
                          loginAttempts: req.flash('loginAttempts')
                        });
                      };

                      var successPostLog = function (req, res) {
                        var loginAttempts = res.locals.req.user.loginAttempts;
                        if (loginAttempts >= 4){
                          recaptcha.verify(req, function(error){
                            if(error){ //Falla de verificacion de captcha
                              res.render('login/get.html', {
                                layout: 'layout/auth.html',
                                entorno: config.config_entorno.empresa,
                                message: req.flash('loginMessage'),
                                loginAttempts: loginAttempts,
                                captcha:recaptcha.render()
                              });
                            } else { //Exito de verificacion de captcha
                              res.redirect('/');
                            }
                          });
                        } else {
                          res.redirect('/');
                        }
                      };

                      var successGetLogout = function(req, res) {
                        req.logout();
                        res.redirect('/');
                      };

                      router.route('/auth/login').get(successGetLog);

                      router.route('/auth/login').post(passport.authenticate("local-login", {failureRedirect: '/auth/logout'}), successPostLog);

                      router.route('/auth/logout').get(successGetLogout);

                      /**
                      * Encuesta Local Login
                      */
                      var successGetPortalLog = function(req, res) {
                          if (req.query.rut != undefined || req.query.token == 'bciboost') {
                              if (req.query.rut != undefined && req.query.token == 'bciboost') {
                                  console.log('casi');
                                  req.body = {
                                      rut: req.query.rut,
                                      password: 'null'
                                  };
                                  passport.authenticate('portaleval-link-login', function(err, user, info) {
                                      if (err) {
                                          return next(err);
                                      }
                                      if (!user) {
                                          res.render('portalevaluacionapp/portal_evaluacion_login.html', {
                                              layout: 'layout/empty.html',
                                              entorno: config.config_entorno.empresa,
                                              message: req.flash('loginMessage'),
                                              access: req.path,
                                          });
                                      }
                                      req.logIn(user, function(err) {
                                          if (err) {
                                              return next(err);
                                          }
                                          if (user) {
                                              res.redirect('/evaluaciones');
                                          }
                                      });
                                  })(req, res, next);
                              } else {
                                  res.render('portalevaluacionapp/portal_evaluacion_login.html', {
                                      layout: 'layout/empty.html',
                                      entorno: config.config_entorno.empresa,
                                      message: 'Existe un problema al iniciar sesión',
                                      access: req.path,
                                  });
                              }
                          } else {
                              if (Object.keys(req.session.passport).length !== 0 && req.session.passport.constructor === Object && req.path === '/auth/evaluaciones' && req.session.passport.user.type === 'PortalEval') {
                                  res.redirect('/evaluaciones');
                              } else {
                                  res.render('portalevaluacionapp/portal_evaluacion_login.html', {
                                      layout: 'layout/empty.html',
                                      entorno: config.config_entorno.empresa,
                                      message: req.flash('loginMessage'),
                                      access: req.path,
                                  });
                              };
                          }
                      }

                      var successPostPortalLog = function(req, res) {
                        res.redirect(req.path.replace('/auth', ''));
                      };

                      var successGetPortalLogout = function(req, res) {
                          req.logout();
                          res.redirect(req.path.replace('/logout', ''));
                      };

                      var successGetPortalRelatorLogout = function(req, res) {
                          req.logout();
                          res.redirect("/auth/relatores");
                      };

                      if (req.path === '/auth/evaluaciones' || req.path === '/auth/evaluaciones/antesdelcurso' || req.path === '/auth/evaluaciones/despuesdelcurso') {
                        var rutAux = req.body.rut;
                        req.body = {
                            rut: (typeof rutAux === 'undefined' || rutAux === '')? 'null': req.body.rut,
                            password: 'null'
                        };
                      }

                      router.route('/auth/evaluaciones').get(successGetPortalLog);
                      router.route('/auth/evaluaciones/antesdelcurso').get(successGetPortalLog);
                      router.route('/auth/evaluaciones/despuesdelcurso').get(successGetPortalLog);

                      router.route('/auth/evaluaciones').post(passport.authenticate("portaleval-login", {failureRedirect: '/auth/evaluaciones'}), successPostPortalLog);
                      router.route('/auth/evaluaciones/antesdelcurso').post(passport.authenticate("portaleval-login", {failureRedirect: '/auth/evaluaciones'}), successPostPortalLog);
                      router.route('/auth/evaluaciones/despuesdelcurso').post(passport.authenticate("portaleval-login", {failureRedirect: '/auth/evaluaciones'}), successPostPortalLog);

                      router.route('/auth/evaluaciones/logout').get(successGetPortalLogout);
                      router.route('/auth/evaluaciones/logout/antesdelcurso').get(successGetPortalLogout);
                      router.route('/auth/evaluaciones/logout/despuesdelcurso').get(successGetPortalLogout);

                      var successGetRelatorLog = function(req, res) {
                          res.render('portalrelatoresapp/portal_relatores_login.html', {
                              layout: 'layout/empty.html',
                              entorno: config.config_entorno.empresa,
                              message: req.flash('loginMessage'),
                              access: req.path,
                          });
                      };


                      var successPostRelatorPortalLog = function(req, res) {
                        res.redirect(req.path.replace('/auth', ''));
                      };




                      router.route('/auth/relatores').get(successGetRelatorLog);
                      router.route('/auth/relatores').post(passport.authenticate("portalrelatores-login", {failureRedirect: '/auth/relatores'}), successPostPortalLog);
                      router.route('/auth/relatores/logout').get(successGetPortalRelatorLogout);



                      break;
                    default:

                      break;
                  }

                  if (controller != '') {
                    var controllerDynamic = require(module);

                    controllerDynamic.req = req;
                    controllerDynamic.res = res;

                    /**
                     * Auth validation
                     */
                    if (privacity == 'private') {
                      if (req.isAuthenticated()) {
                        if (session == 'General') {
                          if (controllerDynamic.auth.indexOf('PortalEval') != -1) {
                            var err = new Error(402);
                            throw err;
                          }
                        } else
                        if (session == 'PortalEval') {
                            if (controllerDynamic.auth.indexOf('General') != -1) {
                                var err = new Error(401);
                                throw err;
                            }
                        } else
                        if (session == 'RelatorEval') {
                            if (controllerDynamic.auth.indexOf('General') != -1) {
                                var err = new Error(401);
                                throw err;
                            }
                        }
            //==============================================================================
                         else
                        if (session == 'PortalRelator') {
                          if (controllerDynamic.auth.indexOf('PortalRelator') == -1) {
                            var err = new Error(402);
                            throw err;
                          }
                        }
            //==============================================================================
                         else {
                            var err = new Error(404);
                            throw err;
                        }
                      } else {
                        if (controllerDynamic.auth.indexOf('PortalEval') != -1) {
                            var err = new Error(402);
                            throw err;
                        } else
                        if (controllerDynamic.auth.indexOf('General') != -1) {
                            var err = new Error(401);
                            throw err;
                        } else {
                            var err = new Error(404);
                            throw err;
                        }
                      }
                    }

                    /**
                     * Check the "auth" atribute of a controller
                     */
                    // if (controllerDynamic.auth.indexOf(controllerPrototype) != -1) {

                    // }

                    /**
                     * Final validation
                     */
                    var isValid = true;
                    if (aryUrl.length > 4) {
                      isValid = false;
                    }

                    if (method == '') {
                      isValid = false;
                    }

                    if (typeof controllerDynamic[controllerPrototype] !== "function") {
                      isValid = false;
                    }

                    if (isValid) {
                        router.route(url)[method](function(ctrlReq, ctrlRes){
                            controllerDynamic[controllerPrototype](ctrlReq, ctrlRes);
                        });
                    } else {
                      res.status(404).send('Not found');
                 }
                  }

                  next();

                } catch (e) {
                  if (e.message == 401) {
                    res.status(401).redirect('/auth/login');
                  } else
                  if (e.message == 402) {
                    res.status(401).redirect('/auth' + url);
                  } else {
                    res.status(404).send('Not found 2');
                  }
                }
              });

              app.use('/', router);
            };

in fact that console.log(touch) get called twice if the route doesn't respond fast (in less than 8 minutes) i had no idea what is going on

Thanks guys!



via Gary V

MongoDB Deeply Nested

I am have some difficulties with deeply nested arrays within MongoDB. I am using mongoose and my project consists of micro-services that all currently use the same database collection. Is it possible to use the below example with how deeply nested it is? If so, how would one access the "questionUser" , "questionTitle", or "questionContent". I currently am able to add course and lesson titles. when I am trying to add question data the correct router is getting hit, but it just hangs and times out and all the data going through is null.

I have condensed the data example below. I am working with MEAN Stack. I also am not seeing any errors, it is just hanging. Not sure where or how to start troubleshooting this. I am not against redesigning my db, but would like to keep with nested/embedded structure somehow but would need a little guidance on how i might look to change it. Please let me know if any further info would be needed to ensure this is clear.

Thank you.

Database

{
 "_id": "593bc9fbbc083a8200eb9b36",
  "courseTitle": "Course 101",
  "courseActive": true,
  "lessons": [
    {
      "lessonTitle": "Lesson about widgets",
      "_id": "593bcecc0799cd89a87ce53e",
      "lessonActive": true,
      "questions": [
        {
            "questionUser": "user1",
            "_id" : "dadsfjlkj23o21",
            "questionTitle": "title",
            "questionContent": "stuffff",
            "answers" : [
                {
                    "answerUser": "user2",
                    "_id": "asdfk231191837d",
                    "answerContent": "the answer is simple",
                    "comment": [
                        {
                            "commentUser": "user1",
                            "_id": "asdkjfawow8183",
                            "commentBody": "That makes sense, thanks!"
                        }
                        ]
                }
                ]
        }
        ]
    }
  ]
}



via bemon

npm init not working and getting stuck on version

So I am using version 8.1.0 of Node.Js and when I call npm init to set up a project it goes to version and stays there. i have tried pressing enter or quitting with ^C but nothing happens. I have waited for over an hour and it hasn't progressed at all. Any idea what I should do?

Here is basically what I am seeing: npm init error



via Belos

MongoClient not returning data in cucumberjs test

I've taken this apart several different ways. If I comment out the this.accounts.remove... it works. If I leave it in there it doesn't. My understanding of cucumberjs, mongo client and node indicates that it should work.

Can someone help me figure out how to get this working?

World.js:

var db = new Db('FlashCards', new Server('localhost', 27017));

db.open(function(err, opened) {
  if (err) {
    console.log("error opening: ", err);
    done(err);
  }
 db = opened;
});

var {
  defineSupportCode
} = require('cucumber');

function CustomWorld() {

  this.db = db;
 this.accounts = db.collection('accounts');

hooks.js:

Before(function(result, done) {
  //comment this out, and leave a done(), it works!!!!
  this.accounts.remove(function(error, result){
    if( error) {
      console.log("Error cleaning the database: ", error);
      done(error);
    }
    done();
  })
});

user_steps.js:

Then('I will be registered', function(done) {
  let world = this;
  this.accounts.find({
    username: world.user.username
  }).toArray(
    function(err, accounts) {
      if (err) {
        console.log("Error retrieveing data: ", err);
        done(err);
      }
      console.log("Accounts found: ", accounts);
      expect(accounts).to.be.ok;
      expect(accounts.length).to.be.equal(1);
      done();
   });
});

Inovcation:

cucumber-js --compiler es6:babel-core/register



via Jim Barrows

Infinite loop uploading file multer/express

I'm trying to make it possible to upload an excel file on a web application. But when I upload my file, there is an inifnite loop on the web application but the file is correctly uploaded, here is the code :

Node :

        var storage = multer.diskStorage({
           destination: function(req,file,cb){
              cb(null,'/uploads/')
            },
           filename: function(req,file,cb){
             cb(null, file.originalname);
           }
        });

    var upload = multer({ storage : storage });

    app.post('/upload', upload.single('file'), function(req,res) {
        var tmp_path = req.file.path;
        var target_path = './uploads/'+req.file.originalname;
        var source = fs.createReadStream(tmp_path);
        var dest = fs.createWriteStream(target_path);
        source.pipe(dest);
});

Angular :

$scope.uploadFile = function(){
var file = $scope.myFile;
var uploadUrl = "/upload";
var fd = new FormData();
fd.append('file',file);

$http.post(uploadUrl,fd,{
     headers: {'Content-Type' : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}
});



via Tewan

Adding server-side libraries for javascript

I am currently coding my offline game into an online game by use of node.js and socket.io

In my game, I use vectors from a library called p5.js to store position of player, collision related movement, etc.

However, the server side (a txt file called "server.js") does not have p5.js like the client, so I can't send information about the player's with vectors.

Here is my question: How could I make the server.js file have access to my p5.js library?

Note: Simply sending x and y values, and then using them to make a vector would be a difficult solution, as I would no longer be able to send a single array holding all the information of all players. Also, enemies, food, trail positions, and much more also depend on vectors. Coverting all of these would be difficult to code.



via Canatron

Get values from Objects

I am writing code to get the XML from a site and parse it.

I want to get all titles from the parsed json. How can I do that?

How can I get the values of the Objects from a key (parsed Json) using NodeJS?

parsed JSON:

[ { title: [ 'NOS Nieuws' ],
    link: [ 'http://nos.nl' ],
    description: [ 'NOS Nieuws' ],
    language: [ 'nl' ],
    copyright: [ 'Copyright NOS' ],
    pubDate: [ 'Sat, 10 Jun 2017 20:50:35 +0200' ],
    webMaster: [ 'podcast@nos.nl (NOS Podcast Beheer)' ],
    'atom10:link': [ [Object], [Object] ],
    'feedburner:info': [ [Object] ],
    item: 
     [ [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object],
       [Object] ] } ]

JS:

  var test = JSON.stringify(data, null, 2);

  var obj = JSON.parse(test);
 console.log(obj.rss.channel);

Thanks.



via Teun

Itterate over json keys with only EJS

Using only EJS (in EJS templates in .ejs files for NodeJS), how would I iterate over keys of an object (that's not an array)?

I'm looking for something like this:

The object like so:

the_object = {
    1: "belongs to id 1",
    3: "belongs to id 3",
    12: "belongs to id 12"
}

Some EJS templating like so:

<% for (key, value: the_object) { %>
    <li>the key is: <%= key %></li>
<% } %>

To produce something like:

  • the key is: 1
  • the key is: 3
  • the key is: 12

Is this possible?



via Alexander Kleinhans

Decrease variable value of all children firebase

How can I update a child value of all children in Firebase Cloud Functions? I found other answers using regex and AngularFire, and some updating on a single level (this is 2 levels) but is there any way to quickly decrease all child variables of a certain key? For example:

database -
     posts -
       RaNd_0MK3y1-
          variable: x
       RaNd_0MK3y2
          variable: y

and decrease all values of variable by 1 upon calling the Cloud Function?



via Spruce Campbell

How to use a handlebars layout to render many different pages

Basically, I want to have a layout that handles everything except the body of my page.

Then, I want to have 4-5 partials that then are rendered in the body of that layout.

I am unsure how to do this. I also need to be able to pass the layout parameters, and the page parameters. Is this possible?

Thank you.



via Sammy Roberts

Angular code in Codeship then Heroku

I would like to post a basik Angular code to Codeship then heroku. But I have a problem what i can't solve. I got this error. I searched, i found a that node version is too old, but my node version in my computer is the newest 6.11.0, npm 3.10.10.

    {
  "name": "anonymous",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "http-server dist -p $PORT",
    "build": "ng build",
    "test": "ng test --single-run",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ng build --aot -prod"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/cli": "1.1.1",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "core-js": "^2.4.1",
    "http-server": "^0.10.0",
    "node-wget": "^0.4.2",
    "rxjs": "^5.1.0",
    "wget": "0.0.1",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/language-service": "^4.2.1",
    "@types/jasmine": "2.5.45",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}

I don't know where to set node version in an angular project.



via Dóczi Szilárd

Retrieve IP from AWS SDK describeAddresses

I'm trying to get the Ip of my AWS EC2 instance in a var, from a remote Node server. The describeAddresses function works well but I can't find a way to get the IP outside the callback. In particular:

function getIP() {
    var return_ip;
    var response = ec2.describeAddresses(ip_params,function(err, data){
        if (err) {
            console.log("Error", err);
        } else {
            //console.log("Success", data.Addresses);
            var IP = data.Addresses[0].PublicIp;
            //This is the IP I should access outside
        }
    });
    //return return_ip;
}

I can't add any parameter in ip_params nor in the callback nor in the describeAddresses function (as all these are defined in the SDK itself).

All help and pointers appreciated !



via Zick

Passing function on express js Route not working

I'm just really new on Node and Express. Trying to pass a function instead of text on my route but it seems not working. I just looked up at documentation there, They mentioned only text with req.send() method. I'm trying to pass here function's but it's not working. and also the alert() not working like this req.send(alert('Hello world')) it say's alert isn't defined or something similar.

I'm trying to do here pass functions like this

function blaBla() {
    //Things to do work here...
}

app.get('/', (request, response) => {  
  response.send(blaBla());
})

**Instead of **

app.get('/', function (req, res) {
  res.send('Hello World!')
})

I hope you guy's understood my question.



via Small developer

How to create new db connection for client without restart service

How to create new db connection for client without restart service

Let's say I have app.js service. whenever new client connect to service , we will check if mongodb connection is already establise for new client or not(check db connection corssponding to client id)

if not available then we will fatch server ip,dbname ,collection name from file and connect to db,and reply to user

Here we can add new client add and corrsponding info to Client Info at any time.

Client Info ClientId: ServerIp : Database Name :Collection Name



via Aakash Kag

Getting data from mlab without request i.e. reloading the page to show in front end

So I know a lot of people has asked questions similar to mine, but I have a different problem. What I am hoping for is to retrieve data from my database in mlab without reloading the page. For example a current game score(in my example cricket score) is added to my db in mlab, now I want this new score in my front end web page without router request i.e. wanting a user to reload the page. Technologies I know and I am using is mongodb, mongoose, nodejs and express.

And I think angular or AJAX is going to help me but i have no idea about them. So please explain clearly and in detail.



via Vanshaj Behl

Parse XML from site and get values from elements

I am writing a NodeJS script to get the XML from a website and get the values from a specific element.

However, when running it it says 'undefined'.

Code:

var http = require('http');
var xml2js = require('xml2js');

var parseString = require('xml2js').parseString;

var req = http.get("http://feeds.nos.nl/nosnieuwsvideo?format=xml", function(res) {
  // save the data
  var xml = '';
  res.on('data', function(chunk) {
    xml += chunk;
    console.log(xml);
  });

 res.on('end', function() {
      parseString(xml, function(err, result) {
      console.log(result['title']);
      });
    });
 });

req.on('error', function(err) {
  // debug error
});

What's the problem?

Thanks



via Teun

how to manually uninstall node , npm and angular cli completely globally n locally

On my Windows 7 machine, I'm unable to update/uninstall an existing global angular-cli instance following the approach outlined https://github.com/angular/angular-cli

using these following commands npm uninstall -g @angular/cli npm cache clean npm install -g @angular/cli@latest

i tried to uninstall angular cli then nodejs and afterwards installed latest nodejs and angular cli. then after when i run ng -v i get errors. so i want to completely uninstall node , npm and angular cli globally and locally completely so that i can install fresh copy.



via angular user

Error Sqlite in NodeJS using Sequelize

Console show this message. By default the foreign key for a belongsTo relation will be generated from the target model name and the target primary key name. SO: Windows10

Error Sqlite Users and Tasks



via Otávio Augusto

restify request uploading file

I am creating a upload file method with my api which uses restify.

I am using postman for making the request, when I am using no header, it works just fine and upload the image, When I use the header:

content-type: application/x-www-form-urlencoded

I get this message:

"message": "Cannot read property 'originalname' of undefined"

How can I make the data not undefined with the header?



via Victor Oliveira

Server rendering react-router v4 passthrough

In react-router v3 we could know when server side rendering had not matched against the current url. This allowed me to pass the request to my express.static middleware instead of sending the rendered App.

In react-router v4, we must use

    const htmlData = renderToString(
        <StaticRouter
            location={req.url}
            context={context}
        >
            <App/>
        </StaticRouter>
    );

in order to render on the server side. However, it automatically redirects everything to /. Why does this behavior even exist? Couldn't we just have an error like we expect insted of it silently failing?

How could I know that nothing matched so that I can call next() and have the other express's routes do the job?

Here is the whole function which I'd like to use:

app.get('*', (req, res, next) => {
    const context = {};
    const htmlData = renderToString(
        <StaticRouter
            location={req.url}
            context={context}
        >
            <App/>
        </StaticRouter>
    );

    console.log(JSON.stringify(context, null, 4)); // empty object
    if (context.url) { // <------------------------ Doesn't work (taken from example and thought it would contain the unmatched url)
        winston.info(`Passing ${req.url} along`);
        next(); // <--------------- Never called even if no route matches.
    } else {
        res.send(pageContent.replace('<div id="main"></div>',
            `<div id="main">${htmlData}</div>`));
    }
});

I tried doing stuff based on this but the // somewhere else is so precise, I couldn't understand it at all.

Here is my last attempt in case it is of any help. This is the Router.jsx file where I plan to define all my Routes.

import React from 'react';
import PropTypes from 'prop-types';
import {
    BrowserRouter,
    Route,
} from 'react-router-dom';
import App from './components/App.jsx';

export const Status = ({ code, children }) => (
    <Route render={({ staticContext }) => {
        if (staticContext) {
            staticContext.status = code;
        }
        return children;
    }}/>
);

Status.propTypes = {
    code     : PropTypes.number.isRequired,
    children : PropTypes.node.isRequired,
};

export const NotFound = () => (
    <Status code={404}>
        <div>
            <h1>Sorry, can’t find that.</h1>
        </div>
    </Status>
);

class Router extends React.Component {
    render() {
        return (
            <BrowserRouter>
                <div>
                    <Route exact path="/" component={App}/>
                    <Route component={NotFound}/>
                </div>
            </BrowserRouter>
        );
    }
}

export default Router;



via Ninetainedo

"Overpaying" a price with knapsack in node

I have this array of items with their prices (property is a random ID, value is the price itself):

var myItems = [{"10222689013":445.49},{"10421477049":54.21},{"10501187481":39},{"8387873996":39},{"10378860764":36.96},{"6260427541":31.83},{"10375621839":26.52},{"5263786797":25.13},{"10465039747":20.34},{"10479336223":18.93},{"10354237608":13.53},{"10384012706":12.22},{"10378859760":6.31},{"10350491915":5.75},{"10441942463":5.3},{"6232326311":4.36},{"7254487888":3.06},{"10274407041":2.84},{"10505002708":2.84},{"10505002635":2.84},{"10505002575":2.84},{"10505002983":2.84},{"10505002850":2.84},{"9558577114":2.84},{"9558577179":2.84},{"10093009482":2.84},{"10515811944":2.84},{"10515812014":2.84},{"10515812058":2.84},{"10093009494":2.84},{"10093009908":2.84},{"10093010135":2.84},{"10505002791":2.84},{"10093018649":2.84},{"10093018673":2.84},{"10515812127":2.84},{"10515812176":2.84},{"10515812216":2.84},{"10515812281":2.84},{"10515812344":2.84},{"10515812423":2.84},{"10093020096":2.84},{"10274407251":2.84},{"10274407222":2.84},{"10274407178":2.84},{"10274407146":2.84},{"10274407111":2.84},{"10274407084":2.84},{"10505002922":2.84},{"10274407017":2.84},{"10274406979":2.84},{"10274406951":2.84},{"10274406693":2.84},{"10274406675":2.84},{"10274406649":2.84},{"10274406619":2.84},{"10274406597":2.84},{"10274406562":2.84},{"9909942264":1.33},{"10501504755":0.54},{"9719056291":0.54},{"10423821338":0.54},{"10525934448":0.54},{"10454361875":0.54},{"10454362211":0.54},{"10501507364":0.54},{"10501507003":0.54},{"10525934421":0.54},{"9538738322":0.54},{"10501505461":0.54},{"10525934368":0.54},{"10501505076":0.54}]

I am trying to create a function that uses knapsack to overpay a given price. (Note that the classic knapsack principle will fill up a "bag" as far as possible, but it won't overfill it.)

I am currently using this module: https://www.npmjs.com/package/knapsack-js

var knapsack = require('knapsack-js');

function prepare(price){
    var result = knapsack.resolve(price, myItems);
    var totalPrice = 0;
    for(var i = 0; i < result.length; i++){
        var itemID = Object.keys(result[i])[0]
        var itemPrice = result[i][itemID]
        console.log("> ID: " + itemID + " | " + itemPrice.toFixed(2) + "$")
        totalPrice += itemPrice;
    }
    console.log(">>>> Total price: " + totalPrice.toFixed(2))
}

prepare(21) 

This will give this output:

> ID: 10515812423 | 2.84$
> ID: 10093020096 | 2.84$
> ID: 10354237608 | 13.53$
> ID: 10501507364 | 0.54$
> ID: 10501507003 | 0.54$
> ID: 9719056291 | 0.54$
>>>> Total price: 20.83

So with this as an example:
20.83 is the "cheapest" combination of items that will still fit into the 21 I gave to the function.

What I am trying to do is however, have the "cheapest" combination that is ABOVE the given number. It could add another one of the cheapest items (0.54) so the price would be 21.37, which is greater than 21.

This can surely be done by removing all the objects that were used with knapsack from the original array, calculate the price-difference and then loop through the array and add the first item that is greater than the difference.

But there musst be a more efficient way, right?



via Thomas Weiss

EmberJS ember-load-initializers error after newer npm install

So our app is using EmberJS. As part of our process when we build a new release we run npm install which installs required Node modules for the project and bower install which installs the required Bower stuff.

This this was working great until a month and a half ago when doing npm install broke the project. I had no idea what the issue was but the project worked fine with the last release's node_modules directory so we just kept using that.

After some investigation once I got time I found that the problem breaks in the ember-load-initializers node module, though it has to be an issue in some other dependency because when I replace the module with the version that works it gets the same error. So I'm thinking the problem is elsewhere.

This is the error I get in the js console in Chrome:

Uncaught TypeError: Cannot read property 'camelize' of undefined
    at http://localhost:4200/assets/vendor-7d0d937efb193a7279d8dcf4910a71fb.js:80947:51
    at Array.forEach (native)
    at exports.default (http://localhost:4200/assets/vendor-7d0d937efb193a7279d8dcf4910a71fb.js:80939:8)
    at Module.callback (http://localhost:4200/assets/########-4fdb2c0e669c00ca0f41cc58f6fd8f9d.js:618:41)
    at Module.exports (http://localhost:4200/assets/vendor-7d0d937efb193a7279d8dcf4910a71fb.js:110:32)
    at requireModule (http://localhost:4200/assets/vendor-7d0d937efb193a7279d8dcf4910a71fb.js:34:18)
    at http://localhost:4200/assets/########-4fdb2c0e669c00ca0f41cc58f6fd8f9d.js:5760:3
        (anonymous) @ index.js:25
        exports.default @ index.js:17
        (anonymous) @ app.js:20
        Module.exports @ loader.js:105
        requireModule @ loader.js:29
        (anonymous) @ app-boot.js:2

I've censored out identifying information with ### but basically it's the app name.

Here is the error line in the script:

  var module = require(moduleName, null, null, true);
  if (!module) {
    throw new Error(moduleName + ' must export an initializer.');
  }

--> var initializerType = _ember2.default.String.camelize(dep.matches[1].substring(0, dep.matches[1].length - 1));
  var initializer = module['default'];
  if (!initializer.name) {
    var initializerName = moduleName.match(/[^\/]+\/?$/)[0];

Not really sure how to debug this further. At first I assumed maybe one of the packages in the repo broke but this has persisted for months now.



via Alexander Rose