Saturday 15 April 2017

JWT Token Based Authentication in Nodejs

i am creating backend api and implementing token based authentication using jwt in nodejs. i am having following error when i try access the login route in postman

http://localhost:3000/authenticate

and the error is

Server listening on port 3000 events.js:160 throw er; // Unhandled 'error' event ^

TypeError: secret must be a string or buffer
at typeError (/Users/sohailawan-awok/portfolioapp/backend/node_modules/jwa/index.js:16:10)
at Object.sign (/Users/sohailawan-awok/portfolioapp/backend/node_modules/jwa/index.js:32:13)
at Object.jwsSign [as sign] (/Users/sohailawan-awok/portfolioapp/backend/node_modules/jws/lib/sign-stream.js:23:24)
at Object.module.exports [as sign] (/Users/sohailawan-awok/portfolioapp/backend/node_modules/jsonwebtoken/sign.js:146:16)
at /Users/sohailawan-awok/portfolioapp/backend/app/controllers/user.controller.js:56:21
at model.Query.<anonymous> (/Users/sohailawan-awok/portfolioapp/backend/node_modules/mongoose/lib/model.js:3683:16)
at /Users/sohailawan-awok/portfolioapp/backend/node_modules/kareem/index.js:273:21
at /Users/sohailawan-awok/portfolioapp/backend/node_modules/kareem/index.js:127:16
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
[nodemon] app crashed - waiting for file changes before starting...



via Sohail

AWS Lex / Alexa and Lambda : How does the Lex app call my Lambda function? event.request.type is undefined

I'm extremely new to Node.js and the Lex service, but after searching online for 2 hours I'm amazed I cannot find an answer to my problem.

I'm trying to create an Alexa / Lex app which simply prompts for variables used to generate a call to a RESTful URL and then read the string reply from that URL.

For my first effort, I'm simply asking for a text file and prompting for the subdomain. This is my Lambda code:

'use strict';

var https = require('http');

const handlers = {

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

"GetCustomerVersion": function() {
    var endpoint = "https://"+{customer}+".services.com/sample.txt"
    var body = ""
    https.get(endpoint, (response) => {
      response.on('data', (chunk) => { body += chunk })
      response.on('end', () => {
        context.succeed(
          generateResponse(
            buildSpeechletResponse(`Customer ${customer} has info `+body, true),
            {}
          )
        )
      })
    })
},

'SessionEndedRequest': function () {
    this.emit(':tell', this.t('STOP_MESSAGE'));
}

}

// Helpers
function buildSpeechletResponse (outputText, shouldEndSession) {

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

}

function generateResponse (speechletResponse, sessionAttributes) {

return { version: "1.0", sessionAttributes: sessionAttributes, response: speechletResponse }

}

exports.handler = (event, context, callback) => {
try {
    if (event.request.type === 'LaunchRequest') {
        handlers['LaunchRequest'](event.request,
            event.session,
            (sessionAttributes, speechletResponse) => {
                callback(null, buildResponse(sessionAttributes, speechletResponse));
            });
    } else if (event.request.type === 'IntentRequest') {
        handlers['GetCustomerVersion'](event.request,
            event.session,
            (sessionAttributes, speechletResponse) => {
                callback(null, buildResponse(sessionAttributes, speechletResponse));
            });
    } else if (event.request.type === 'SessionEndedRequest') {
        handlers['SessionEndedRequest'](event.request, event.session);
        callback();
    }
} catch (err) {
    callback(err);
}
};

I'm pretty sure the way I'm building the endpoint inGetCustomerVersion is wrong, but the real problem is that when I test the lambda function itself I get this error:

{
  "errorMessage": "Cannot read property 'type' of undefined",
  "errorType": "TypeError",
  "stackTrace": [
    "exports.handler.err (/var/task/index.js:86:26)"
  ]
}

I know it's yelling about the event.request.type and either event or event.request is undefined, but I have no clue what causes them to be undefined -- I thought they were being populated by the call itself.

Is there some documentation or tutorial I can read / watch to see more about this? Everything I've seen seems to have a different interface to the Alexa app (where I'm using the Lex portal in AWS), but I wouldn't expect the LAMBDA code to differ.... but maybe that's my confusion? It's an issue of "I don't know what I don't know" so any guidance is welcome.

Thank you!



via Bing

In a single threaded language like JavaScript, does it ever make sense to open and close database connection per transaction?

From a perspective of Node.js and server side scripting (web applications), does it ever make sense to open and close database connections per transaction?

Consider MongoDB and MySQL. If all web requests are going to transact with the database in some way, it seems most efficient to maintain a single persistent connection on server start and use it at the time of each request. The connection will close when the server is stopped.

This question is founded on a potentially fallible assumption that queries can be issued against a database cluster. That is to say... a single open connection from any web server in a load balanced farm would scale just fine as long as the database cluster can support the corresponding number of open connections.

As an example, I create database operations object on top of the database connection itself, I have designed a single connection for MongodB in the following manner:

Mongo.connect(MONGO_URL, function(err, db) {

  Mongo.ops = {};

  Mongo.ops.find = function(collection, json, callback) {
    db.collection(collection).find(json).toArray(function(err, docs) {
      if(callback) callback(err, docs);
    });
  };

  Mongo.ops.insert = function(collection, json, callback) {
    db.collection(collection).insert(json, function(err, result) {
      if(callback) callback(err, result);
    });
  };
});

In this example I avoid object modeling wiht Mongoose on purpose, taking advantage of the inherent flexibility of JSON in a NoSQL database. The same principle can be applied to the MySQL Node.js Driver to some extent.



via ThisClark

I want to get result json from goeuro api

I am developing API in java to get json from GoEuro API Hosted API are available at github. i want to know parameter i need to send with POST method and get result as json and combined with my custom logic.

Here is my java code to call api.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class JsonEncodeDemo {
    public static void main(String[] args) {
        try {

            URL url = new URL("http://www.goeuro.com/GoEuroAPI/rest/api/v3/search?departure_fk=318781&departure_date=16%2F04%2F2017&arrival_fk=380553&trip_type=one-way&adults=1&children=0&infants=0&from_filter=Coventry+%28COV%29%2C+United+Kingdom&to_filter=London%2C+United+Kingdom&travel_mode=bus&ab_test_enabled=");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");

//          conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()), "UTF-8"));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }

            conn.disconnect();

        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }
}

I am not good in nodejs. Any Help would be appreciated.



via Uttam Kasundara

Looking for a cleaner way to run NodeJS as a service with absolute paths

I have a NodeJS project that starts with server.js under /opt/battleship. If I cd to that dir and type node server, everything works correctly, but if I sit in /root and use an absolute path to start it up, such as node /opt/battleship/server, then everything I serve from its ./lib and ./public subdirs gets a 404 response. This is a problem in production because my /etc/init/battleship.conf script specifies starting the process on boot with

exec /usr/local/bin/node /opt/battleship/server.js >> /var/log/battleship.log 2>&1

It runs, but then I get the 404 errors. If I put the line

cd /opt/battleship

just above that in the battleship.conf file, I don't get 404 errors, I get all my files correctly, but it seems as if using cd in a .conf file is messy and prone to errors. Correct me if I'm wrong, this is my first handwritten .conf file. Is there a better way to have my server.js server up files correctly from its ./lib and ./public subdirectories? Below is my server.js file for reference:

var PORT      = 3000;

var requirejs = require('requirejs');
var http      = requirejs('http');
var fs        = requirejs('fs');
var path      = requirejs('path');
var mime      = requirejs('mime');
var cache     = {};

requirejs.config({
    baseUrl: __dirname,
    nodeRequire: require,
        packages: [
            {name: 'ship', location: 'public/js/lib/ship'},
            {name: 'GameState', location: 'public/js/lib', main: 'GameState'}
    ]   
});

requirejs(['./lib/battleship_server'], function(battleship_server) {
    function send404(response) {
        response.writeHead(404, {'Content-Type': 'text/plain'});
        response.write('Error 404: response not found.');
        response.end();
    }

    function sendFile(response, filePath, fileContents) {
        response.writeHead(
            200,
            {'Content-Type': mime.lookup(path.basename(filePath))}
        );
        response.end(fileContents);
    }

    function serveStatic(response, cache, absPath) {
        if (cache[absPath]) {
            sendFile(response, absPath, cache[absPath]);
        } else {
            fs.exists(absPath, function(exists) {
                if (exists) {
                    fs.readFile(absPath, function(err, data) {
                        if (err) {
                            send404(response);
                        } else {
                            cache[absPath] = data;
                            sendFile(response, absPath, data);
                        }
                    });
                } else {
                    send404(response);
                }
            });
        }
    }

    var server = http.createServer(function(request, response) {
        var filePath = false;

        if (request.url === '/') {
            filePath = 'public/index.html';
        } else {
            filePath = 'public' + request.url;
        }
        var absPath = './' + filePath;
        serveStatic(response, cache, absPath);
    });

    server.listen(PORT, function() {
        console.log('Server listening on port ' + PORT + '.');
    });

    battleship_server(server);
});



via Zack Stauber

Is cookie still used?

While I was reading about cookies, I tried the following in browser console:- document.cookie = "username=John Doe";

result:- SecurityError (DOM Exception 18): The operation is insecure.



via Rohit Bhardwag

How to distribute ssl private keys for nodejs https module

I am trying to use the https module for my nodejs server. I have the certificate and intermediate CA certificates in my repository, as they are public. However, I do not know how to store and distribute the certificate's private key, which I need to instantiate the server. I am using elastic beanstalk to deploy my code, so generating certs on the host machine won't work (at least I don't think so).



via bsm

Node: Get image from PDF whose URL has weird query string

As part of #1917Live, I've made a Twitter bot that tweets 100-year-old New York Times articles about Russia.

It uses the New York Times' Article Search API to get the articles and then uses twit to tweet them.

I also try to make the tweets more engaging, like an actual newspaper would try to do. So I parse the headlines to make them more readable, tag users that are part of #1917Live, and add a hashtag.

Now here's the part where I'm stuck. Each article comes with a URL to a pdf file showing how it looked when it was printed. Here's an example. I want to download that pdf, convert the first page into an image, and attach the image to the tweet. This is the simplified code I tried to use to get the PDF:

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

var url = "http://query.nytimes.com/mem/archive-free/pdf?res=9500E4DC153AE433A25756C1A9629C946696D6CF";

var file = fs.createWriteStream("file.pdf");
var request = http.get(url, function(response) {
  response.pipe(file);
});

But this does not work. If I were trying to download a normal pdf file, with a .pdf file extension, I suspect I wouldn't be having any problems. But this is different. Any help would be very much appreciated.



via hazards

How to schedule jobs to run at different times for different users

I am building a feature that allows the user to schedule a report to be generated by the server.

i.e. User A wants to schedule the report to be generated and emailed to him at 5 PM every day whereas User B wants to schedule the same at 10 AM every day.

There can be many users wanting the job to run at any time of their choosing.

I see there is something called node-schedule: https://www.npmjs.com/package/node-sched...

where you can do this:

var schedule = require('node-schedule'); 

var j = schedule.scheduleJob('42 * * * *', function(){ 
    console.log('The answer to life, the universe, and everything!'); 
}); 

to execute a cron job when the minute is 42 of each hour.

Something like this might work if the system only has one user, but for multiple users, I can't hardcode the time to schedule the job. Any suggestion?



via Sam

Silo-ed Multi-SPA with Vue JS, Node JS & Express

I am just starting out with Vue JS and need guidance on project structure for creating a multiple-SPA front-end.

The idea is to have a common navigation bar at the top of all pages. Each link on the nav-bar leads to another static html page. Each static html page will have a simple div container that will load the necessary compiled js file (compiled with webpack) that will have the necessary components for that pages's functionality.

Specifically I need suggestions on the following aspects.

  1. Webpack Configuration.
  2. Project Structure.

I am using an Express based backend Json Web API.

Presently I do not require state sharing between the silo-ed pages.



via Raghavendra Kumar

Hello World Angular2 app with typescript

I am practising my first program in angular2 and I have some deviations from the expected output .

typings.json:

{
  "ambientDependencies": {
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd",
    "jasmine": "github:DefinitelyTyped/DefinitelyTyped/jasmine/jasmine.d.ts#5c182b9af717f73146399c2485f70f1e2ac0ff2b"
  }
}

tsconfig.json

{

  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

package.json

{
  "name": "angular2-helloworld-example",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install"
  },
  "license": "ISC",
  "dependencies": {
    "angular2": "2.0.0-beta.15",
    "systemjs": "0.19.26",
    "es6-shim": "^0.35.0",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.6.10"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings":"^0.7.12"
  }
}

index.html

<!DOCTYPE html>
<html>  
  <head>
    <title>My First Angular 2 App</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- 1. Load libraries -->
    <!-- IE required polyfills, in this exact order -->
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
    <script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>

    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

    <!-- 2. Configure SystemJS -->
    <script>
      System.config({
        packages: {
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>
  </head>

  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

Inside the app folder there are 2 files:

app.component.ts

import { Component } from 'angular2/core';

@Component({
  selector: 'my-app',
  templateUrl: '<h1> Hello </h1>'
})
export class AppComponent {     
}

main.ts

import { bootstrap }    from 'angular2/platform/browser';  
import { AppComponent } from './app.component';

bootstrap(AppComponent); 

When I run the command, npm start the server is running without any errors but the output is: Loading...

My expected output is :

'<h1> Hello </h1>'

whats it that I am missing?



via user1400915

how to migrate swagger document 1.2 to 2.0?

What is the easiest way to make swagger version 2.0 documents using existing node.js APIs?

Currently I am using node-swagger-express npm. The generates swagger documents's version is 1.2.

Except using swagger-converter in command line, what is the easiest way to migrate swagger 1.2 to swagger 2.0?

I installed npm swagger, and it saids that swagger-editor@2.10.5 requires higher node version (>= 5.8.0)



via user2884721

Socket hang up when using axios.get, but not when using https.get

To the best of my knowledge, I am doing the same thing using 2 different approaches:

const https = require("https");
const axios = require("axios");

let httpsAgent = new https.Agent({rejectUnauthorized: false});

axios.get(`https://${hostname}:${port}${path}`, {httpsAgent})
    .then((data) => { console.log("axios success: " + data.substr(0, 100)); })
    .catch((error) => { console.log("axios error: " + error); });

let data = "";
https.get({ hostname, path, port, agent: httpsAgent },
    (response) => {
        response.on("data", (chunk) => { data += chunk; });
        response.on("end", () => { console.log("https success: " + data.substr(0, 100)); });
    })
    .on("error", (error) => { console.log("https error: " + error); });

When I run this code, i get 2 different outcomes:

PS C:\Users\me> .\node\node.exe .\generate-test-data.js
axios error: Error: socket hang up
https success: [{"cool":"data"...

What is going on here? I have a feeling it has to do with asynchronicity, but not quite sure how... Can somebody give me a hint as to how/why these 2 behaviors are different?



via Lucas

Deleting empty Child node with causing seg fault

The purpose of the code is to insert a new node into a binary tree, but rather then the left root or right root in the tree be set to Null it is the left and right roots are pointing to empty nodes. So when inserting a new normal node into the tree there is a old empty node in hanging out. How would I be able to delete this empty node? I need to be able to delete this empty node, because when I run my clear a seg fault is caused

// insert in a normal_node
    //   Postcondition: Returns a pointer to this node.
    //
    //   Implementation note:
    //     - If this node is holding the value `k`, insert does nothing but
    //       return the `this` pointer.
    //     - Otherwise, depending on how the value `k` compares with the data
    //       in this node, insert makes a recursive call to insert `k` on either
    //       the left- or right-subtree of this node (and returns the `this`
    //       pointer).
    node * normal_node::insert(int k)
    {
        if (this -> getData() == k)
        {
            return this;
        }
        if (k > this -> getData())
        {
            right = getRight() -> insert(k);
            return this;

        }
        else
        {
            left = getLeft() -> insert(k);
            return this;
        }

}
// clear
//   Deletes all the descendants of this node.
//   Postcondition: This node is a leaf.
//   Implementation note:  Use recursive divide-and-conquer.
void normal_node::clear()
{
    if (!this -> isLeaf())
    {
        this -> getRight() -> clear();
        this -> getLeft() -> clear();
        if (this -> getRight() != this || this -> getLeft() != this)
        {
            delete this -> getLeft();
            delete this -> getRight();
        }

    }
}



via Terriyon Veasy

implementing Left-pointer info right-pointer for java binary tree

i have been assigned a hw assignment about converting a list into a binary tree that i am having trouble wrapping my head around the concept, I have been reading through examples but i cant figure out how to actually use it. I need a left node pointer, information, and right pointer. I have found code to add but dont understand how to use it.

class Node{ int data; Node left; Node right; public Node(int data){ this.data = data; left = null; right = null; }

is this all i need to do my program, i dont understand how im suppose to assign left and right values to each node. Do i need a name for each node i insert. I have psuedo code for my hw such as

y=avail;  //whats avail? this is my first line
treeRoot = y;
info(y) = x[2];   //(im inputing from an array) how do i assign this?
lptr(y)=z;     // (left pointer of y gets z) z maybe a pointer?



via Tim E

How to upload binary data to s3 using node js using s3 key attribute

I need to download and extracted files from s3 bucket and upload to another bucket.The files are downloaded properly and the result is returning as binary data using s3.getObject.

I need to pass the binary data to upload the files to s3.

But I dont know what name has to give for "Key" params in s3.putOBject when we push the binary data to s3.putObject. Kindly help me.

This is my code

s3.getObject(params, function(err, data,callback) {
if (err) {
    console.log(err);
    callback(err);
} 
else {
    zlib.gunzip(data.Body, function (err, result) {
        if (err) {
            console.log(err);
        } else {
            var extractedData = result;
            s3.putObject({
            Bucket: "bucketName",
            Key: "filename",
            Body: extractedData,
            ContentType: 'content-type'
            }, function (err) {
                 console.log('uploaded file: ' + err);
            });
        }
    });
  }
});



via vishnu

How to starting a basic nodejs server?

I am learning nodejs to develop a app of mine. So I'm starting with the basic of the basic : creating a node server.

Here is the code :

var http = require(http);

http.createServer(function(req,res){

res.writeHead(200, {'content-type':'text/plain'});
res.end('Hello world');
}).listen(9001);

console.log('server is running on port 9001');

and what my console returned to me

gdiop@localhost:~/Desktop/learning/node.js> node index.js

assert.js:81
  throw new assert.AssertionError({
  ^
AssertionError: missing path
    at Module.require (module.js:495:3)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/gdiop/Desktop/learning/node.js/index.js:1:74)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:393:7)
gdiop@localhost:~/Desktop/learning/node.js> 

Am I missing something here ... ?



via Gabriel D.

How to create a TCP/IP echo server in Electron.js?

i'm trying to create a simple tcp/ip server in electron.js. I declare my server after

app.on('ready', function(){
    createWindow()
})

function something like that

const net = require('net')

net.createServer(function(sock) {
    console.log('Server has been started')
    console.log('Client connected: ' + sock.remoteAddress +':'+ sock.remotePort)

    sock.on('data', function(data) {

        console.log('DATA ' + sock.remoteAddress + ': ' + data)
        sock.write(data)
    });
    sock.on('close', function(data) {
        console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort)
    });

}).listen(10003, 'localhost')

but when i try to connect to server nothing happens. What do i wrong?



via DWilde

Auth0 "service not found" error

I'm attempting to use Auth0 to issue JWT tokens for accessing my API (so that Auth0 handles all the OAuth and security concerns, etc., and my API just needs to check the token). When I try to test the Authorization Code flow for clients to receive an access token (using Node + Express), the following happens:

  • The authorization code request works fine, and the client is redirected back to my redirect_uri with the code appended to the query. All good.

  • The token request then always fails. If I include the audience parameter, the request returns an access_denied error with the following details: Service not found: {the audience parameter}, regardless of what value I set for the audience parameter.

  • If I don't include the audience parameter, I get a server_error with the message Service not found: https://oauth.auth0.com/userinfo.

I've checked every Auth0 setting and read every documentation page thoroughly, and so far nothing has worked. I've also tested the Authorization Code flow in Auth0's API debugger, and it worked fine. My test follows exactly the same parameters, and yet still receives an error requesting the token. I'm testing on localhost. The client credentials and implicit flows are working fine.

Here is a test endpoint I created which retrieves the authorization code from Auth0:

const qs = require('querystring');

const getCode = (req, res) => {
  const params = {
    audience,                            // the value of the API Audience setting for the client
    client_id,                           // the client ID
    redirect_uri,                        // the redirect_uri, which is also listed in the Allowed Callback URLs field
    response_type: `code`,
    scope:         `offline_access open` // ask to return ID token and refresh token,
    state:         `12345`,
  };

  const authDomain = `mydomain.auth0.com`;
  
  res.redirect(`${authDomain}/oauth/authorize?${qs.stringify(params)}`);

};

The redirect_uri then redirects to the following endpoint, where I make the request for the access token:

const https = require('https');

const callback = (req, res) => {

  const body = {
    client_id,
    client_secret,
    code:          req.query.code,
    grant_type:    `authorization_code`,
    redirect_uri,  // same value as provided during the code request
  };
  
  const opts = {
    headers:  { `Content-Type`: `application/json` },
    hostname: `mydomain.auth0.com`,
    method:   `POST`,
    path:     `/oauth/token`,
  };
  
  const request = https.request(opts, response => {
    let data = ``;
    response.on(`data`, chunk => { data += chunk; });
    response.on(`error`, res.send(err.message));
    response.on(`end`, () => res.json(JSON.parse(data))); // this executes, but displays the error returned from Auth0
  });
  
  request.on(`error`, err => res.send(err.message));
  request.end(JSON.stringify(body), `utf8`);

};

Any suggestions as to what I might be doing wrong?



via dwhieb

Insert specific Node in index Linked List on Python

i have sort of problem imagining or solving this, i have this node and list

class node:
    def __init__(self, info):
        self.info = info
        self.next = None

class list:
    def __init__(self):
        self.__first = None
        self.__last = None

and i have to create a function, called indexL(self, info, position), that put the exact node in the desired position, here is what i have for now (i have created already a method called self.length() to give the size of the list)

def indexL(self, info, position):
    longit = self.length()
    n = node(info)
    p = self.__first
    if index == 0:
        self.__first = n
    else:
        if index > 0 and index < longit:
           if index == tam-1:
                self.__last = n
            else:

and now i'm stuck there, if someone want to help or any recommendation, i would be really grateful



via Esteban

Node.js - Display my own google analytics data to visitors

I am struggling to authenticate on server side.

I would like to display my own data from Google Analytics to my site's visitors. Every manual, API, or tutorial I can find explains how to use OAUTH2 to authenticate users.

ie: https://github.com/google/google-api-nodejs-client#alpha https://developers.google.com/analytics/devguides/reporting/embed/v1/core-methods-reference https://developers.google.com/analytics/devguides/reporting/core/v2/authorization and so on.

With that, I do not need to authenticate users because it's not their accounts I would like to access, but rather my own.

This is what I am using:

var google = require('googleapis');
var scopes = ['https://www.googleapis.com/auth/analytics.readonly']
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(auth.googleAPI);
var analytics = google.analytics("v3")
console.log(analytics.data.ga.get({
    ids:"ga:107290894",
    "start-date":"2016-01-01",
    "end-date":"2017-04-15",
    "metrics":'ga:sessions,ga:pageviews',
}))

But I get the following error:

{ [Error: Login Required]
code: 401,
errors: 
 [ { domain: 'global',
   reason: 'required',
   message: 'Login Required',
   locationType: 'header',
   location: 'Authorization' } ] }

through auth.googleAPI I am passing the client id, secret and public key, and every other piece of information that was in the JSON file I got from google when I created a Service Account Key.

What am I doing wrong?



via Michael Seltenreich

Failed exitCode=-4071

I am following this guide. Having problem deploying to azure.

https://docs.microsoft.com/en-us/azure/app-service-web/app-service-web-nodejs-sails#step-3-configure-and-deploy-your-sailsjs-app

Full Error

    remote: Failed exitCode=-4071, command="D:\Program Files (x86)\nodejs\6.9.1\node.exe" "D:\Program Files (x86)\npm\3.10.8\node_modules\npm\bin\npm-cli.js" insta
ll --production

also

    remote: npm ERR! EINVAL: invalid argument, rename 'D:\home\site\wwwroot\node_modules\.staging\spdx-license-ids-3f30671f' -> 'D:\home\site\wwwroot\node_modules\
sails-hook-grunt\node_modules\grunt-contrib-cssmin\node_modules\maxmin\node_modules\pretty-bytes\node_modules\meow\node_modules\normalize-package-data\node_mod
ules\validate-npm-package-license\node_modules\spdx-correct\node_modules\spdx-license-ids'

Thanks



via Logan_B

Nodejs Mysql callback in callback

Hello I'm stuck in my first callback "selectArticleByTitle(title, callback)", the terminal send "Cannot read property 'id' of undefined". I don't know how to force the first callback to finish this and launch the others.

 router.get('/article/:title', function(req, res){
    dataBase.selectArticleByTitle(req.params.title, function(db_titleERR, db_titleResults){
      dataBase.selectArticle(db_titleResults[0].id, function(db_resultsArticleERR, db_resultsArticle) {
        //Get id of the previous article
        dataBase.previousArticle(db_titleResults[0].id, function(db_previousIdERR, db_previousId){
          //Get id of the next article
          dataBase.nextArticle(db_titleResults[0].id, function(db_nextIdERR, db_nextId){
            //Get lastArticle
            dataBase.lastArticle(function(db_lastArticleERR, db_lastArticle) {
              });
            });
          });
        });
      });
    });
});



exports.selectArticleByTitle = function(title, callback){
  connection.query('select * from article where title=?', [title], function(err, row){
    if(err)
      callback(err, null);
    else{
      if(row){
        callback(null, row);
      }
    }
  });
}

Thank you in advance



via David Manutea

Bulk-delete items from a firebase database in node.js

I'm trying to delete all nodes with a date greater than '2017-04-05' with a bulk operation with a firebase function. Can you spot what I'm doing wrong here?

The 2 nodes that should get deleted are the ones in red: enter image description here

Here's the code that is failing - can you see what's wrong? Also, I'm concerned about the performance of this (I'll only run it once in a while though). If there are millions of games in the list, should that concern me if I only run this once a day?

exports.remove = functions.https.onRequest((req, res) => {

    const deleteBeforeDate = req.query.deleteBeforeDate;

    var ref = admin.database().ref('games');

    var keysToDelete = {};
    for (var game in this.games) {

        var date = items[i]['.date'];
        if(date.value > '2017-04-05'){
            keysToDelete[game.key] = null;
        }
    }
    this.ref.update(keysToDelete);
});

Thank you very much,

Mike



via Mike Gagnon

Is there a node.js method to read an index.html file and add new elements?

I am trying to read my index.html file from my server.js in order to add a new

  • that links to a new html file I generate. I am using the POST method to do this and can successfully generate the new HTML file, however I am not sure how I can add a new
  • inside the index.HTML.

Here is my server.js:

    //POST method
  if(req.method === 'POST'){
    req.on('data', (data) => {
      let elementObj = querystring.parse(data.toString());
      element = elementObj.elementName;
      elementSymbol = elementObj.elementSymbol;
      elementAtomic = elementObj.elementAtomicNumber;
      elementDescription = elementObj.elementDescription;

      let newElement = fs.createWriteStream(`./public/${element}.html`);
      newElement.write(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The Elements - ${element}</title>
<link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<h1>${element}</h1>
<h2>${elementSymbol}</h2>
<h3>Atomic number ${elementAtomic}</h3>
<p>${elementDescription}</p>
<p><a href="/">back</a></p>
</body>
</html>`);

      let indexElements = document.querySelector('#elements');
      let li = document.createElement('li');
      let a = document.createElement('a');
      a.setAttribute('href', `/${element}.html`);
      let elem = document.querySelector(`a[href = "/${element}.html"]`);
      elem.innerHTML = `${element}`;

      indexElements.appendChild(li);
      li.appendChild(a);

      res.end(data);
    });
  }

Here is my index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>The Elements</title>
  <link rel="stylesheet" href="/css/styles.css">
</head>
<body>
  <h1>The Elements</h1>
  <h2>These are all the known elements.</h2>
  <h3>These are 2</h3>
  <ol id = 'elements'>
    <li>
      <a href="/hydrogen.html">Hydrogen</a>
    </li>
    <li>
      <a href="/helium.html">Helium</a>
    </li>
  </ol>
<script src="../../server.js"></script>
</body>
</html>

The result I want in my newly, modified index.html (new 'Boron' <li> added):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>The Elements</title>
  <link rel="stylesheet" href="/css/styles.css">
</head>
<body>
  <h1>The Elements</h1>
  <h2>These are all the known elements.</h2>
  <h3>These are 2</h3>
  <ol id = 'elements'>
    <li>
      <a href="/hydrogen.html">Hydrogen</a>
    </li>
    <li>
      <a href="/helium.html">Helium</a>
    </li>
    <li>
      <a href="/boron.html">Boron</a>
    </li>
  </ol>
<script src="../../server.js"></script>
</body>
</html>



via Colin Sygiel

Why is it not possible to call functions directly from an object without function expression?

function Car(make, model) {
    this.make = make
    this.model = model

    console.log(" Iam inside the object" )
    this.whatsmymodel = function () {
        console.log(" Iam " , this.model)
    }

    function whatsmymake() {
        console.log(" Iam " , this.make)
    }
}

function whatsthis() {
    console.log (" This is a function")
}

Car.prototype.whoami = function () {
        console.log(" Iam " , this.make + " " + this.model)
}

var tesla = new Car("Tesla", "ModelS")
tesla.whoami()
tesla.whatsmymodel()
tesla.whatsmymake() // Error!!

whatsthis()

How come I get error for tesla.whatsmymake()

TypeError: tesla.whatsmymake is not a function

I understand it is possible in the new ES6 class but wouldnt it be easier to define a function within a function constructor ? It is letting me define but doesnt allow me to call - why is that ?



via Victor

Rewrite URL parameter when using node.js and express without a redirect

I am using node.js, express, and sockets.io to:

  1. Find out whether or not the user has included a specific URL parameter when they arrive (working)
  2. If not, make a new random room ID and join the user to that room (working)
  3. Modify the address bar of the browser to reflect the new URL without redirecting the browser (unsure if possible, or how to accomplish)

First, I do not know if this is possible without violating DOM security. If it is, I would like to understand how I might be able to do it.

If it is not possible, and/or if I need to use a redirect, could you show me how to do it within my already working code within the working context of items #1 and #2?

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var url = require('url');

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

app.get('/', function(req, res, next) {
  res.sendFile(__dirname + '/index.html');
  var roomID = req.query.me;
    if (roomID == null || !io.sockets.adapter.rooms[roomID]) {
      console.log("URL room variable is: " + roomID);
      console.log('New room!');
      roomID = Math.random().toString(36).substring(2, 13);
      joinRoom(roomID);
      console.log("+ you just joined new room: " + roomID);
    } else {
      joinRoom(roomID);
      console.log("URL room variable is: " + roomID);
      console.log("= you just joined existing room: " + roomID);
    }
});

function joinRoom(roomID) {
  io.on('connection', function(socket) {
    socket.join(roomID);
    io.sockets.in(roomID).emit('connectToRoom', "Joined room: http://localhost:3030/?me=" + roomID);
  });
  return;
}

server.listen(3030);

I do not have any sample code for the part that I'm trying to accomplish because I simply don't know where I should begin. So I would appreciate any direction (redirection? pun intended).

Thank you!



via Dshiz

Mongoose error in required properties

I'm connecting a Angular 2 app to MongoDB via Mongoose. I'm trying to store some data, but i obtain an error on all required properties.

I set up a schema, serverside:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var uniqueValidator = require("mongoose-unique-validator");

var schema = new Schema({
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    nome: {
        type: String,
        required: true
    },
    cognome: {
        type: String,
        required: true
    },
    dataNascita: {
        type: Date
    },
    telefono: {
        type: String
    },
    classifica: {
        type: String
    }
});

schema.plugin(uniqueValidator);

module.exports = mongoose.model("User", schema);

The user object is clearly filled:

User Object

Mongoose responds with an error:

Error Object

Thanks in advance for any help. Max

Update:

The call from a Angular service:

@Injectable()
export class AuthService {

    constructor(private http: Http) {

    }

    addUser(utente: Utente) {
        const body = JSON.stringify(utente);
        return this.http.post('http://localhost:3000/utente', body)
            .map((response: any) => {
                console.log(response);
                response.json();
            })
            .catch((error: Response) => Observable.throw(error.json()
            ));
    }
}

The Moongose call:

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

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

router.post('/', function (req, res, next) {
    var user = new User({
        email: req.body.email,
        password: req.body.password,
        nome: req.body.nome,
        cognome: req.body.cognome,
        dataNascita: req.body.dataNascita,
        telefono: req.body.telefono,
        classifica: req.body.classifica
    });
console.log(res);
    user.save(function (err, result){
        console.log(err);
        console.log(res);
        if (err){
            return res.status(500).json({
                titolo: "Errore durante il salvataggio",
                errore: err
            });
        }
        res.status(201).json({
            messaggio: 'Utente salvato correttamente',
            oggetto: res
        });
    });
});



via Max Bertoli

npm search result sort anomaly

I'm looking for a node.js stopwatch package, so I tried what seemed to be an obvious enough search:

https://www.npmjs.com/search?q=stopwatch&page=1&ranking=popularity

However, that's giving me as the first result a package called stopwatch which has only 33 downloads in the last month, and as the second result a package called nanotimer which has 19015 downloads in the last month, so it's not presenting descending order of popularity as specified.

What am I missing?



via rwallace

Limiting entries in JSON Object

Alrighty! I'm working on small chat add-on for my website, and when a user logs on they'll see the chat history, I'm using a JSON Object to store all messages in my NodeJS server, now I'd like it so whenever more than fifty entries are in the Object it adds the latest message and removes the oldest, I'd like this to limit my server from handling a lot of messages every time a user logs on. How would I be doing this?

Here's how I store my messages,

            var messages = {
                "session":[

                ]
            };

            messages.session.push(
                {
                    "name":user.name,
                    "message":safe_tags_replace(m.msg),
                    "image":user.avatar,
                    "user":user.steamid,
                    "rank":user.rank,
                }               
            );

I could also just do loading the last fifty messages in the JSON Object but whenever I run my server for a long time without restarting it this Object will become extremly big, would this be a problem?



via Martijn Ebbens

Get current page in .ejs file?

I have simple Node.js web app with login/registration functionality through passport. In the nav bar I have two buttons: Login and Register. What I would like to do is when the user is on the Registration page, only display the Login button in the nav bar, when the user is on the Login Page only display the Register button in the nav bar. How can I achieve this in my header ejs file?

I tried this:

<% if (document.URL.contains("login")) { %>
    <li><a href="/login">Sign In</a></li>
<% } else { %>
    <li><a href="/register">Sign Up</a></li>
<% } %>

Problem with this is that the document variable is not defined in my ejs locals...and I don't think I can define it as a local? At least when I tried I get an error that document is not define...makes sense since this is done in the app.js file.

How can I achieve this functionality?

Thanks!



via user2573690

How to use "this" inside a callback?

I have a rest service on the other end of the url in my code below that returns the names of all of the objects in an s3 bucket. I'm trying to create a simple Alexa skill that tells me how many objects are in that bucket. My problem is that within the http get request the term "this" is not referencing the same thing as it is outside of the http get request. How can I use "this" inside the get request or return the "count" variable from my http get request?

"use strict";
var Alexa = require("alexa-sdk");
var Client = require('node-rest-client').Client;

exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.registerHandlers(handlers);
    alexa.execute();
};

var handlers = {
    'Launch Request': function() {
        this.emit('CountItems');
    },
    'ContentsIntent': function() {
        this.emit('CountItems');
    },
    'CountItems': function() {
        var client = new Client();
        var count = undefined;
        client.get("URL", function (data, response) {
            console.log(data['Keys'].length);
            count = data['Keys'].length;
        });
        this.emit(':tell', 'There are ' + count + ' items in your s3 bucket.');
    }
};



via Chris Bell

How read lock status in NodeJs?

I am running an external python code in NodeJs. The python code send command to the usb controller which interacts with a lock. The commands can be one of the following three:

  • Open
  • Close
  • Status

I am able to succesfully send open/close command, but I am trying to see how to work out the status command. The status command simply state the status of the current lock such as open3, or close2, but i need to grab that information and figure out a way to display it to console once that command is issued.

Below is how the open/close command are sent:

 var comport = rows[i].comport;
          var command = "open" + rows[i].cubby_id;
          var commandClose = "close" + rows[i].cubby_id;


          console.log(command);
          console.log(comport);


          var options = {
            scriptPath: 'python/scripts',
            args: [command, comport, commandClose] // pass arguments to the script here

          };


          PythonShell.run('controlLock.py', options, function (err, results) {
            if (err) throw err;
            console.log('results: %j', results);
          });

I tried sending the status command, but the results return is null.

Below, are the possible command that can be sent. enter image description here

Below is the controlLock.py (without status)

import serial
import sys
import time

# 0 is the script itself, technically an argument to python
script = sys.argv[0]

# 1 is the command arg you passed
command = sys.argv[1]

# 2 is the comport arg you passed
comport = sys.argv[2]

commandClose = sys.argv[3]


ser = serial.Serial()
ser.baudrate = 38400 #Suggested rate in Southco documentation, both locks and program MUST be at same rate 
ser.port = "COM{}".format(comport) 
ser.timeout = 5 
ser.open() 
#call the serial_connection() function 
ser.write(("%s\r\n"%command).encode('ascii'))
time.sleep(5)
ser.write(("%s\r\n"%commandClose).encode('ascii'))



via John

Modularizing Multer Functionality Issue

I am trying to clean up my controllers by modularizing my multer module functions, which allow me to upload multiple files with my forms. The current code presented below works, but I want put the multer function in a new file. I assumed that simply taking the function and exporting it from another file would work, but for some reason I'm hitting a time out during my form POST, despite calling the console.log at the start of the multer code. It appears that something within that code is stopping the process, but no error message is thrown. Does anyone see what might be causing the error?

Multer called within route file:

var aws = require('aws-sdk');
var multer = require('multer');
var multerS3 = require('multer-s3');
var moment = require('moment');

var uploadDate = new moment().format("YYYY-MM-DD");
var s3 = new aws.S3();
var options = {
    Bucket: process.env.AWS_BUCKET,
    Expires: 60
};

if(app.get('env') === 'production' || app.get('env') === 'staging'){
    options.ACL = 'private'
} else {
    options.ACL = 'public-read'
};

//////////Multer code being called

var upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: options.Bucket,
        contentType: multerS3.AUTO_CONTENT_TYPE,
        acl: options.ACL,
        key: function(req, file, cb){
            var fileNameFormatted = file.originalname.replace(/\s+/g, '-').toLowerCase();
            cb(null, req.session.organizationId + '/' + uploadDate + '/' + fileNameFormatted);
        }
    }),
    fileFilter: function(req, file, cb){
        if(!file.originalname.match(/\.(jpg|jpeg|png|gif|csv|xls|xlsb|xlsm|xlsx)$/)){
            return cb('One of your selected files is not supported', false);
        }
        cb(null, true);
    }
}).array('fileUpload', 5);

///////Post route calling multer and rest of form submission

.post(function(req, res){

     upload(req, res, function(){
        if(err){
            console.log('Multer upload error');
            req.flash('error', err);
            res.redirect(req.get('referer'));
            return;
        }

        ... MORE CODE ...
    })
});

/controllers/multer.js, which contains the multer code:

var express = require('express');
var app = express();
var aws = require('aws-sdk');
var multer = require('multer');
var multerS3 = require('multer-s3');
var moment = require('moment');

var s3 = new aws.S3();
var uploadDate = new moment().format("YYYY-MM-DD");

var options = {
    Bucket: process.env.AWS_BUCKET,
    Expires: 60,
    //ContentType: req.query.file_type
};

if(app.get('env') === 'production' || app.get('env') === 'staging'){
    options.ACL = 'private'
} else {
    options.ACL = 'public-read'
};

module.exports = {

    //Annotation file upload
    annotationFileUpload: function(){
        multer({
            storage: multerS3({
                s3: s3,
                bucket: options.Bucket,
                contentType: multerS3.AUTO_CONTENT_TYPE,
                acl: options.ACL,
                key: function(req, file, cb){
                    console.log("key called");
                    var fileNameFormatted = file.originalname.replace(/\s+/g, '-').toLowerCase();
                    cb(null, req.session.organizationId + '/' + uploadDate + '/' + fileNameFormatted);
                }
            }),
            fileFilter: function(req, file, cb){
                console.log("file filter called");
                if(!file.originalname.match(/\.(jpg|jpeg|png|gif|csv|xls|xlsb|xlsm|xlsx)$/)){
                    return cb('One of your selected files is not supported', false);
                }
                cb(null, true);
            }
        }).array('fileUpload', 5);
    }
}

Importing /controller/multer and calling route:

var multerFile = require('./components/multer');

    .post(function(req, res){

    multerFile.annotationFileUpload(req, res, function(err){
                if(err){
                    console.log('Multer upload error');
                    req.flash('error', err);
                    res.redirect(req.get('referer'));
                    return;
                }
           ....MORE CODE....
         })
    });



via cphill

AngularJS routing routes to path instead of loading the html page

I am just making a basic AngularJS app from angular-seed which currently has:

  • index.html
  • app.js
  • home/home.html
  • home/home.js

Now, I want to redirect to home.html when I click on an li item Home with href="/home". This does okay, but it redirects me to directory structure instead of the file.
The files -
app.js

'use strict';
// Declare app level module which depends on views, and components
angular
    .module('mentorSpot', [
      'ngRoute',
      'mentorSpot.home'
    ])
    .config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
      $routeProvider.when('/home', {
        templateUrl: 'home/home.html',
        controller: 'HomeCtrl'
    });
      $routeProvider.otherwise({redirectTo: '/home'});
    }]);

home/home.js

'use strict';
angular.module('mentorSpot.home', ['ngRoute'])
.config(['$routeProvider'], function($routeProvider){
        $routeProvider.when('/home', {
            templateUrl: 'home/home.html',
            controller: 'HomeCtrl'
        });
    })
.controller('HomeCtrl',[function(){

}]);

home/home.html

<h1>This is the home page</h1>

index.html

<!DOCTYPE html>
<!--[if lt IE 7]>      <html lang="en" ng-app="mentorSpot" class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html lang="en" ng-app="mentorSpot" class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html lang="en" ng-app="mentorSpot" class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="en" ng-app="mentorSpot" class="no-js"> <!--<![endif]-->
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>MentorSpot</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/normalize.css">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/main.css">
  <link rel="stylesheet" href="app.css">
  <script src="bower_components/html5-boilerplate/dist/js/vendor/modernizr-2.8.3.min.js"></script>
  <!-- W3.CSS Framework-->
    <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
    <!-- Fonts -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat">
    <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
    <!-- jQuery and external JavaScript -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="hp.js"></script>
    <script src="https://use.fontawesome.com/d18274d1d9.js"></script>
    <style>
      body,h1,h2,h3,h4,h5,h6 {font-family: "Lato", sans-serif}
      .w3-navbar,h1,button {font-family: "Montserrat", sans-serif}
      .fa-anchor,.f
  </style>
</head>
<body>
  <!-- Navbar -->
  <ul class="w3-navbar w3-blue w3-card-2 w3-top w3-left-align w3-large">
    <li class="w3-quarter w3-center"><h3>MentorSpot.com</h3></li>
    <li class="w3-hide-small"><a href="#/home" class="w3-padding-large w3-hover-indigo">Home</a></li>
    <li class="w3-hide-small"><a href="#htutw" class="w3-padding-large w3-hover-indigo">How to use this website?</a></li>
    <li class="w3-hide-small"><a href="#Catalog" class="w3-padding-large w3-hover-indigo">Courses</a></li>
    <li class="w3-hide-small"><a href="#RegLog" class="w3-padding-large w3-hover-indigo">Register/Login</a></li>
  </ul>
  <div ng-view>

  </div>
  <script src="bower_components/angular/angular.js"></script>
  <script src="bower_components/angular-route/angular-route.js"></script>
  <script src="app.js"></script>
  <script src="/home/home.js"></script>
  <script src="components/version/version.js"></script>
  <script src="components/version/version-directive.js"></script>
  <script src="components/version/interpolate-filter.js"></script>
</body>
</html>

This is what index.html looks like

On clicking home in the above menu I get redirected like this



via Nishit Mengar

can't rebuild on node-gyp even though I installed its dependencies

I followed option 1 here I installed

npm install --global --production windows-build-tools

and install node-gyp global but I have this error below that I cannot fix

enter image description here

node-gyp configure runs ok but i cannot run rebuild. help?



via i am newbie

Async/Await Class Constructor

At the moment, I'm attempting to use async/await within a class constructor function. This is so that I can get a custom e-mail tag for an Electron project I'm working on.

customElements.define('e-mail', class extends HTMLElement {
  async constructor() {
    super()

    let uid = this.getAttribute('data-uid')
    let message = await grabUID(uid)

    const shadowRoot = this.attachShadow({mode: 'open'})
    shadowRoot.innerHTML = `
      <div id="email">A random email message has appeared. ${message}</div>
    `
  }
})

At the moment however, the project does not work, with the following error:

Class constructor may not be an async method

Is there a way to circumvent this so that I can use async/await within this? Instead of requiring callbacks or .then()?



via Popey Gilbert

How do I simultaneously call async functions and wait for all callbacks?

In nodeJS, how do I simultaneously call async functions and wait for all callbacks before proceed?

In the example bellow I want main to return all_results only when f1, f2 and f3 are done with the callback()

function main(){
  var all_results = [];
  f1(function(results){
    all_results.push(result)
  });

  f2(function(results){
    all_results.push(result)
  });

  f3(function(results){
    all_results.push(result)
  });

  // when all 3 calls are complete:
  return(all_results)
}


function f1(callback){
  ...
  callback(results);
}

function f2(callback){
  ...
  callback(results);
}

function f3(callback){
  ...
  callback(results);
}

Not using promises.



via Azevedo

Node.JS crashes, I don't know why

I am creating a Self-Bot in discord.js, I have created a function to make a box like:

╭──────────────────────╮
│        Title         │
├──────────────────────┤
│ A message that was   │
│ auto wrapped.        │
╰──────────────────────╯

But when I was working with this I got this error: <--- Last few GCs --->

[5414:0x102801600]    34628 ms: Mark-sweep 1402.3 (1462.5) -> 1402.2 (1431.5) MB, 1428.1 / 0.0 ms  (+ 0.0 ms in 0 steps since start of marking, biggest step 0.0 ms, walltime since start of marking 1431 ms) last resort 
[5414:0x102801600]    35832 ms: Mark-sweep 1402.2 (1431.5) -> 1402.2 (1431.5) MB, 1203.7 / 0.0 ms  last resort 


<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x1ecd007266a1 <JS Object>
        2: prettiefy [/Users/adm/Desktop/Discord/Client/prettiefy.js:~3] [pc=0x115c254f97bd](this=0x1031bc4e25a1 <an Object with map 0x3b708c34aea1>,s=0x1031bc4e25d9 <an Object with map 0x3b708c34b161>)
        3: run [/Users/adm/Desktop/Discord/Client/prettiefy.js:103] [pc=0x115c255b92d8](this=0x1031bc4e25a1 <an Object with map 0x3b708c34aea1>,str=0x1031bc4e2691 <String[17]: Message|Title|30 >,split=0...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: node::Abort() [/usr/local/bin/node]
 2: node::FatalException(v8::Isolate*, v8::Local<v8::Value>, v8::Local<v8::Message>) [/usr/local/bin/node]
 3: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [/usr/local/bin/node]
 4: v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationSpace) [/usr/local/bin/node]
 5: v8::internal::Runtime_AllocateInTargetSpace(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/local/bin/node]
 6: 0x115c2528ed46
Abort trap: 6

I have no clue why this error happens, here's the code

const wrap = require ('wordwrap');

module.exports.prettiefy = s => { var _Result = '';
  const _default = {
    width: 25, // Prefered width if width is not defined
    title: 0, // having the title as Int(0) will skip titlebar
    message: 'Specify a message!', // Default message if message is not set
    softCorners: true // if false it will not have rounded corners.
  };

  if (typeof s == 'object') {
    if (s.width == undefined) s.width = _default.width;
    if (s.title == undefined) s.title = _default.title;
    if (s.softCorners == undefined || typeof s.softCorners !== 'boolean') s.softCorners = _default.softCorners;
    if (s.message == undefined) s.message = _default.message;
  } else if (typeof s == 'string') { s = {
    width: _default.width,
    title: _default.title,
    message: s,
    softCorners: _default.softCorners
  }; } else { throw new Error('arg[0] be a typeof string or object') }

  let _ = {
    title: (typeof s.title == 'string' ? wrap(0, s.width, {mode:'hard'})(s.title).split('\n') : (typeof s.title == 'number' && s.title == 0 ? '\077' : '' + wrap(0, s.width, {mode: 'hard'})('' + s.title).split('\n')) ),
    msg: wrap(0, s.width, {mode: 'hard'})(s.message).split('\n'),

    corners: {
      soft: ['╭', '╮', '╰', '╯'],
      hard: ['┌', '┐', '└', '┘']
    },

    l: ['─', '│', '├', '┤'],

        c: []
  };

    s.width += 1;

    _.c = _.corners.soft;
    if (!s.softCorners) _.c = _.corners.hard;

    /* Line: 1 aka Start */
    _Result += _.c[0] + _.l[0]; // Beginning: +-
    for (i = 0; i < s.width; i++) _Result += _.l[0]; // Center: --
    _Result += _.l[0] + _.c[1]; // End: -+

    /* Line: 2 aka Title */
    if (s.title !== '\077') {
        for (T = 0; T < _.title.length; i++) {
            _Result += _.l[1] + ' '; // Beginning: |\
            for (i = 0; i < (s.width / 2) - (_.title.length / 2); i++) _Result += ' '; // Center: \
            _Result += _.title; // Center: Message
            for (i = 0.5; i < (s.width / 2) - (_.title.length / 2); i++) _Result += ' '; // Center: \
            _Result += ' ' + _.l[1]; // End: \|
        }

        /* Line: 3 aka Title_Split */
        _Result += _.l[2] + _.l[0]; // Beginning: |-
        for (i = 0; i < s.width; i++) _Result += ' '; // Center: --
        _Result += ' ' + _.l[2]; // End: -|
    }

    /* Line: 4 aka Message */
    for (C = 0; C < _.msg.length; C++) {
        _Result += _.l[2] + _.l[0]; // Beginning: |\
        _Result += _.msg[C] // Center: Message
        for (i = 0; i < s.width - _.msg[C].length; i++) _Result += ' '; // Center: \
        _Result += ' ' + _.l[2]; // End: \|
    }

    /* Line 5 aka End */
    _Result += _.c[2] + _.l[0]; // Beginning: +-
    for (i = 0; i < s.width; i++) _Result += _.l[0];
    _Result += _.l[0] + _.c[3]; // End: -+

    // End;
    return _Result;
};

module.exports.translate = function (str, Splitter = '|', Skipper = '/Skip/') {
    if (typeof str !== 'string') str = '' + String(str);
    var Res = {};

    str = str.split(Splitter);

    /*
        Arg[0]: Message,
        Arg[1]: Title,
        Arg[2]: Width,
        Arg[3]: softCorners
    */

    if (str.length < 1) throw new Error('Need atleast one argument!');

    if (str[0] !== undefined || str[0] == Skipper) Res.message = str[0];
    if (str[1] !== undefined || str[1] == Skipper) Res.title = str[1];
    if (str[2] !== undefined || str[2] == Skipper) Res.width = parseInt(str[2]);
    if (str[3] !== undefined || str[3] == Skipper) Res.softCorners = str[3];

    return Res;
}

module.exports.run = function (str, split) { return module.exports.prettiefy(module.exports.translate(str, split)); }

Does anyone have any clue why this is happening?



via Alliator

SyntaxError loading launchChrome.js in react-native

I am trying to use react-native and react-native-weback-server.

When I run rnws start I get a SyntaxError at node_modules/react-native/local-cli/server/util/launchChrome.js:15

function getChromeAppName(): string {
                           ^
SyntaxError: Unexpected token :

Looking at that file, I see the method:

function getChromeAppName(): string {
  switch (process.platform) {
  case 'darwin':
    return 'google chrome';
  case 'win32':
    return 'chrome';
  default:
    return 'google-chrome';
  }
}

However this does not with my Node version (7.9.0). I don't know what version of Javascript this is valid syntax in and if I'm using the correct babel transpiler.

Here's my NPM dependencies:

  "dependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^6.4.1",
    "babel-plugin-transform-react-jsx": "^6.24.1",
    "babel-preset-es2016": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "coffee-loader": "^0.7.3",
    "coffee-script": "^1.12.5",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-native": "^0.43.3",
    "react-native-webpack-server": "^0.9.3",
    "webpack": "^2.4.1",
    "webpack-dev-server": "^2.4.2"
  }

and webpack.config.js

var path = require('path'); var webpack = require('webpack');

module.exports = {
  entry: './app.coffee',
  output: { filename: 'bundle.js' },
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2016', 'react']
        }
      },
      {
        test: /\.coffee$/,
        loader: "coffee-loader" 
      }
    ]
  },
};



via maxple

FireBase Functions .once('value') method returning undefined

Currently I have started using firebase functions for my project. I went through the sample projects on GitHub and saw some of the sample projects use .once("value") when declaring admin references and returning them in the promises. My problem is the following:

my code: exports.HandleNotifications = functions.database.ref('/users/{user_id}/Friends/pending/{recipient_id}').onWrite(event => {

if(!event.data.exists()){
    return null;
}
console.log(event.data.val());
let recipient_id = event.data.val();
let getrecipientProfile = admin.auth().getUser(recipient_id);
let getDeviceTokens  = admin.database().ref('users/'+event.params.user_id+'/deviceTokens').once('value');
let getRecipientName = admin.database().ref(`/users/${event.params.recipient_id}/displayName`).once('value');

return Promise.all([getDeviceTokens,getrecipientProfile,getRecipientName]).then(others => {

    let tokensSnapshot = others[0];
    let recipient = others[1];
    let recipient_name = others[2];
    console.log(recipient_name);

    // Check if there are any device tokens.
    if (!tokensSnapshot.hasChildren()) {
        return console.log('There are no notification tokens to send to.');
    }
    console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
    console.log('Fetched follower profile', recipient);

    // Notification details.
    const payload = {
        notification: {
            title: 'You have a new Friend Request!',
            body:   recipient.displayName + `requested to follow you.`,
            icon:   recipient.photoURL
        }
    };

    // Listing all tokens.
    const tokens = Object.keys(tokensSnapshot.val());
    return admin.messaging().sendToDevice(tokens,payload);

});

});

output: enter image description here

so executing console.log(recipient_name); returns the following output like in the image: T { A: Rb { B: 'StevenWong', aa: P { k: [Object], aa: null, wb: [Object], Bb: '' }, Bb: null }, V: R { u: Gd { app: [Object], L: [Object], Ua: [Object], Sc: null, ca: [Object], td: 1, Qa: [Object], va: [Object], qg: [Object], jc: [Object], ee: [Object], md: [Object], ia: [Object], Xa: [Object], cd: 1, fe: null, K: [Object] }, path: J { o: [Object], Y: 0 }, m: Df { xa: false, ka: false, Ib: false, na: false, Pb: false, oa: 0, kb: '', bc: null, xb: '', Zb: null, '', g: Tc {} }, Kc: false, then: undefined, catch: undefined }, g: Tc {} }



via Steven W

Gulp v4.0 task series

Hi there I am trying to use gulp 4.0 new feature gulp series. I have gulp functions I am trying to run in a series I also want to be able to call them individually. Both the coffee and vendor task call from a function which returns a promise.

The issue is it is not running a series it is executing coffee the vendor but also calling the allJs task which is the parrent

##
#  Return gulp destinations depending on params
#  FUTURE: This function will be resposible for
#  exectuing the transaltion scripts
#  @param {String} String representation of array of langs if anys
#  @return {promise} Reutrns a promise with a arrray
#  of destionations
##
getDest = (langs, path) ->
  return new Promise (resolve, reject) ->
    #Return default path if no lang specified or reject if no data
    resolve [gulp.dest(buildDir+path)] if !langs
    reject Error 'Empty language param' if typeof langs is Boolean

    str = langs.split(",")

    rtn = [] #Return array of destintion for each lang
    rtn.push gulp.dest("public/" + o + path) for o in str
    resolve rtn


##
#  Complie Vendor javascript files
#  @param {String} none
#  @return {Stream} stream
##
gulp.task 'coffee', (done) ->
  getDest(argv.lang, '/assets/js').then (response) ->
    gulp.src([coffeeSrc],{ base: 'assets' })
    .pipe(logger(
      before: 'Compiling CoffeeScript files ...'
      after: 'CoffeeScript files compiled successfully'
      showChange: silent))
    .pipe(coffee({bare: true}))
    .on('error', gutil.log)
    .on('error', gutil.beep)
    .pipe(uglify())
    .pipe(concat('app.min.js'))
    .pipe(multistream.apply(undefined, response))
    done()
  .catch (error) ->
    console.error 'failed', error
    done(err)



##
# Complie Vendor javascript files
# @param {String} none
# @return {Stream} stream
##
gulp.task 'vendor', (done) ->
  stream = getDest(argv.lang, '/assets/js').then (response) ->
    gulp.src(["./assets/jsv2/vendor/jquery.min.js",vendorSrc])
    .pipe(logger(
      before: 'Compiling vendor javascript files ...'
      after: 'Vendor javascript files compiled successfully'
      showChange: silent))
    .pipe(uglify())
    .pipe(concat('vendor.min.js'))
    .pipe(multistream.apply(undefined, response))
    done()
  .catch (error) ->
    console.error 'failed', error


##
#  Bundle all javascript files
#  @param {String} none
#  @return {Boolean} Finished
##
gulp.task 'allJs', gulp.series 'coffee', 'vendor', (done) ->
  getDest(argv.lang, '/assets/js').then (response) ->
    gulp.src(["./assets/jsv2/vendor/jquery.min.js",
      buildDir + '/**/**/vendor.min.js',
      buildDir + '/**/**/app.min.js'],{ base: 'assets' })
        .pipe(logger(
          before: 'Bundling javascript files ...'
          after: 'Bundled javascript files compiled successfully'
          showChange: silent))
        .pipe(uglify())
        .pipe(concat('all.min.js'))
        .pipe(multistream.apply(undefined, response))
        done()
  .catch (error) ->
    console.error 'failed', error
    done()

Im pretty new to promises and gulp. I just got Visual studio code which is great I was trying to use the debugger but just couldn't figure it, im still a pretty amateur debugger.



via Alex Kirwan

Error: Uncaught (in promise): Error: No provider for GoogleMaps

I am using ionic framework but while integrating google maps i am getting this error : Error: Uncaught (in promise): Error: No provider for GoogleMaps!

this is my map class :

     import { Component,ViewChild } from '@angular/core';
      import { NavController,Platform } from 'ionic-angular';
      import { App, MenuController } from 'ionic-angular';
     import {
     GoogleMaps,
    GoogleMap,
    GoogleMapsEvent,   LatLng,
   CameraPosition,
  MarkerOptions,
  Marker
 } from '@ionic-native/google-maps';
 import { HttpModule } from '@angular/http';
 import { NgModule } from '@angular/core';



  @NgModule({
 imports: [
  HttpModule
]})
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

 map: GoogleMap;
 constructor(public platform: Platform,public navCtrl: 
     NavController,app: App, menu: MenuController,private googleMaps: 
       GoogleMaps) {

     menu.enable(true);
        platform.ready().then(() => {
        this.loadMap();
          });

      }

        @ViewChild('map') mapElement;

// Load map only after view is initialized loadMap(){

       let location = new LatLng(-34.9290,138.6010);

    this.map = new GoogleMap('map', {
      'backgroundColor': 'white',
      'controls': {
        'compass': true,
        'myLocationButton': true,
        'indoorPicker': true,
        'zoom': true
      },
      'gestures': {
        'scroll': true,
        'tilt': true,
        'rotate': true,
        'zoom': true
      },
      'camera': {
        'latLng': location,
        'tilt': 30,
        'zoom': 15,
        'bearing': 50
      }
    });

    this.map.on(GoogleMapsEvent.MAP_READY).subscribe(() => {
        console.log('Map is ready!');
    });

}

}



via sachin kaushik

How to render Markdown using Node.js Express, Mongo and Markdown-it?

I am entirely new to the world of markdown and trying to get my head around it.

I hacked together a basic node Express app. It is reading some sample markdown text from a mongodb database, then using markdown-it middleware to process the markdown.

var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var fs = require('fs');
var path = require('path');

var md = require('markdown-it')({
  html: true,
  linkify: true,
  typographer: true
});

var app = express();

app.set('views', path.resolve(__dirname, 'views'));
app.set('view engine','ejs');

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/mdtest1", function(err, db) {
  if(!err) {
    console.log("We are connected");
  }
});

app.use('/2',function(req,res){
    MongoClient.connect("mongodb://localhost:27017/mdtest1", function(err, db) {
        var collection2 = db.collection('mdcol');
        var ObjectId = require('mongodb').ObjectId;
        var o_id = new ObjectId('58f273ae624c4d435c632fa0');
        collection2.findOne({}, function(err, document) {
            //console.log(document.body);
            console.log('--------------------------------------------------')
            var result = md.render(document.body);
            console.log(result);
            res.render('md', {
                'main': result
            });
        });
    });
});

app.listen(3000);

My question is: how do I render this in a template? I am using ejs templating where the following variable is displayed:

<%= main %>

Bu this displays HTML as text on the page.

What am I doing wrong? Thanks!



via Aivoric

node.js mongoose remove the subset of presisted documents not in a current list of those documents

I have a list of documents I retrieve from a web API. All documents in this list have the same structure and 2 fields combined create a natural key.

I take this list and persist into a collection.

A month of so later I will call for a fresh subset of documents from the API based on a specifically value from one of the 2 fields. However, not all of the documents in the new subset include all the documents previously persisted.

I need to identify and remove old documents not in the fresh subset.

In SQL this is:

delete a from olderset a
left join newersubset b
 on a.f1 = b.f1
  and a.f2 = b.f2
where a.f2 is null
-- or something like that

Think of f1 as companyName and f2 as transactionID. olderset will contain a collection of different companyName/s.

But my newer API call is only getting the transactions of one specific company.

In mongoose, what is the best strategy to remove the company specific older transactions from the olderset collection. When the documents to be removed do not exists in the newersubset list?

Can you offer a code example?



via user2367083

defining function order to mongoose

I have a situation where I'd like to order my data from mongodb defining my own function.

something like that:

  Items
    .find()
    .sort(myFunction())
    .exec(callback);

do someone have some idea how to do that!?



via Eduardo Spaki

How do I deploy my reactJS application on web server public to internet

I started following reatJS tutorial from Youtube, now I want to share my learning step by step with the LEAD developers over internet.

I have npm /node js installed on my macbook, and I after I finish work i run npm start and it gives me local host address on port 8081 , but I have apache web server running on different machine which is open to internet , so I want to deploy my reactJS app using npm / webpack to this computer running apache.

I have this package.json file setup.

{
  "name": "react-basics",
  "version": "1.0.0",
  "description": "Some Basics ReactJS",
  "main": "index.js",
  "scripts": {
    "start": "npm run build",
    "build": "webpack -d && cp src/index.html dist/index.html && webpack-dev-server --content-base src/ --inline --hot",
    "build:prod": "webpack -p && cp src/index.html dist/index.html"
  },
  "keywords": [
    "reactJS"
  ],
  "author": "Sanjeev Kumar",
  "license": "MIT",
  "dependencies": {
    "react": "^15.5.3",
    "react-dom": "^15.5.3"
  },
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",
    "webpack": "^2.3.3",
    "webpack-dev-server": "^2.4.2"
  }
}

and webpack.config.js

var webpack = require("webpack");
var path = require("path");

var DIST_DIR = path.resolve(__dirname, "dist");
var SRC_DIR = path.resolve(__dirname, "src");

var config = {
    entry: SRC_DIR + "/app/index.js",
    output: {
        path: DIST_DIR + "/app",
        filename: "bundle.js",
        publicPath: "/app/"
    },
    module: {
        loaders: [
        {
            test: /\.js?/,
            include: SRC_DIR,
            loader: "babel-loader",
            query: {
                presets: ["react", "es2015", "stage-2"]
            }
        }

        ]
    }



};

module.exports = config;

Do I have to install npm /node.js on remote machine as well which is open to internet ? can I not just use apache web server ? if so how do I just stick to port 80 ?



via Ciasto piekarz

Rebinding 'this' for arrow functions in Node v7.9.x

I want to pass around a function and rebind the this. It works for some function types, but not others.

Here's my sample code:

class F {
  go (fxn) { fxn.apply(this, [1,2]) }
}

var f = new F();
f.foo = 'bar';
f.go(         () => { console.log(this.foo) }); // undefined
f.go(function ()    { console.log(this.foo) }); // "bar"

I understand that this is rebound to the caller's context in fat-arrow functions (and I'm so glad!). I would expect the normal behavior of .apply and .call to override this and re-bind this at runtime.

My question is: is there a way I can accomplish what I'm trying to do here with fat-arrow functions?



via Sir Robert

How to catch subsequent API signatures ?

I am creating an API server with user provided routes. I am stuck how can I write routes that user defined routes are dynamically handled, if the precedent route matches user's token.

I have tried two approaches, One with :params, but that doesn't work as desired as a user might input multiple levels of routes.

router.all('/api/:apikey/:fakeapi', function (req, res, next) {
  logger.debug(`API Key: ${req.params.apikey}, Requested URL: ${req.params.fakeapi}`);

  res.send(`API Key: ${req.params.apikey}, Requested URL: ${req.params.fakeapi}`);
});

Above code, works if route /api/378929832/fine, but fails when route is somehting like api/378929832/fine/with/me.

How can I make it handle all subsequent /xyz/xyz/xyz/... if the precedent API signature matches it.



via errhunter

How to get zone serial of a specific name server with node.js?

With linux you can type: dig @specificnameserver.com google.com SOA +short

How can you do this with node.js? I have tried to find packages to help with this, but I have been unable.



via Kevin Kivi

Exporting object looses prototyped function

I am trying to make my server.js file smaller...so I broke out the multer config into it's own file. But I get TypeError: upload.single is not a function on the upload object I exported.

This was working when I had the whole multer code in server.js, the problem only came when I broke it out into it's own file and exported the object

multer-storage.js

const multer = require('multer');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const path = `listing-pics/${req.body.internalUserID}`;
    mkdirp.sync(path, { opts: { mode: 0755 } } );
    cb(null, path);
  },
  filename: function (req, file, cb) {
    const fileType = file.mimetype.split('/')[1];
    const internalUserID = req.body.internalUserID;
    const filename =
      `${file.fieldname}-${internalUserID}-${Date.now()}.${fileType}`;
    cb(null, filename);
  },
  limits: { fieldSize: 25 * 1024 * 1024 }
});

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

module.exports = {
  upload: upload
} 


server.js:

const upload = require('./app/data/multer-storage');

api.route('/listings/:listingID/images')
  .post(upload.single('image'), apiLogic.listingImages);



via dman

string from lodash .template wont return in node js

For some reason I cant return the string from a lodash template. I can print the string in the function but once the function ends nothing else happens, i.e. console.log doesnt work for the string that was returned or anything for that matter

this is where the function is called

var prompt = stopInfo.getStopStatus(stopNumber);

and this is the function

function stopInfo() {
}

stopInfo.prototype.getStopStatus = function(stopNumber) {
var options = {
  method: 'GET',
  uri: ENDPOINT + '?stopid=' + stopNumber + '&maxresults=1&format=json',
  json: true
};

requestPromise(options).then(function(stopStatusObject) {
  if (true) { // check if error from dublin bus
    console.log(stopStatusObject);
    //var template = _.template('The ${busNumber} bus will arrive in ${dueTime}');
    var template = _.template(' <%= error %>');
    var test = template({
        'error': 'test'
  //    busNumber: stopStatusObject.results.route,
  //    dueTime: stopStatusObject.results.duetime
    });
    console.log(test);
    return test;
  }
}).catch(function(err) {
  console.log("error gettin stop info: " + err);
  var prompt = "I didn\'t have data for stop number " + stopNumber;
  return prompt;
});
};



via user3408117

How to update a JSON file on github from a heroku app

I am working on customizing a GroupMe Bot I forked on GitHub and have run into some trouble. This is my first project working on bots and with Heroku. I want the bot to update a counter in a JSON file every time it recognizes a keyword in a groupchat. Right now I have it posting the current counter(which it pulls from a JSON file) every time it recognizes the keyword, but it does not update the counter in the JSON file. The bot is currently being run on Heroku and the code is deployed through GitHub.

The code that writes to the JSON file works on a simpler version on my local machine and I essentially just copied that part over to the code on GitHub so I do not think that is the problem. Could the problem be that when the app runs it updates the file and does not commit the changes to github or something like that?

Thank you.



via Aaron Rotem

How to delete Cookie when shutting down the server

So everytime I start my nodejs Server I set the userId:

var customerId = null;  

When the user tries to log in I set the cookie :

customerId = myCart.Login(FormData.username, FormData.password);
_setCookie(res, "customerId=" + customerId);

Set cookie:

function _setCookie(res, cookieStr) {
    res.setHeader('set-cookie', cookieStr);
}

The problem is when I close to application and I restart it the cookie is still setted but the customerId is setted to null. This causes the error when I try to logg off the user:

 if (userIsLogedIn(req, "customerId")) {

            _processFormData(req, res,
                (req, res, FormData) => {

                    myCart.LogOffCustomer(customerId);
                    _delCookie(res, "customerId=" + customerId);
                    myWebServer.redirect(res, "Success.html");

                },

                (res) => {
                    myWebServer.redirect(res, "LoggOffFailed.html");
                }
            );


        }
        else {
            myWebServer.redirect(res, "NotLoggedIn.html");
}

Here I check if the user is logged in:

 function userIsLogedIn(httpMessage, cookieName) {

    if (httpMessage.headers.cookie == undefined) {
        return false;
    }
    var cookies = _parseCookies(httpMessage.headers.cookie);

    return cookies[cookieName] != undefined;
}

function _parseCookies(cookieName) {
    var cookies = {};
    cookieName.split(';').forEach(function (cookie) {
        var parts = cookie.match(/(.*?)=(.*)$/)
        cookies[parts[1].trim()] = (parts[2] || '').trim();
    });

    return cookies;
};

So when I try to logg off the user I check if the cookie is setted. The cookie is only setted when the user is loged in. But when I close the server and restart him the userId is null and so I cant logg off the user.It means that I can only logg off the user if I don't close the server. But I wan't it than even when I reset the server I still can logg off the user.



via igodie

How to fix TypeError: sqlDb is not a constructor

I have REST app using pure node.js I have created an HTML server that listens on port 8080 for a GET request. IF the request endpoint is /employees, for example (http://localhost:8080/employees), the response should be a recordset of the employee table. When I make the GET request for (http://localhost:8080/employees I am receiving the following error found is db.js: TypeError: sqlDb is not a constructor

I am stuck at this point and any help would be greatly appreciated.

Here is the js code:

db.js

const sqlDb = require('mssql/msnodesqlv8')
//const sqlDb = require('mssql')
var settings = require("../settings");

    exports.executeSql = function (sql, callback) {
        var conn = new sqlDb.ConnectionPool(settings.dbConfig);
        conn.connect()
            .then(function () {
                var req = new sqlDb(conn);
                req.query(sql)
                    .then(function (recordset) {
                        callback(recordset);
                    })
                    .catch(function (err) {
                        console.log(err);
                        callback(null, err);
                    });
            })
            .catch(function (err) {
                console.log(err);
                callback(null, err);
            });
    };

server.js

    const sqlDb = require('mssql/msnodesqlv8')
    var http = require("http");
    var emp = require("../controllers/employees");
    const settings = require("../settings");

    http.createServer(function (req, resp) {
        switch (req.method) {
            case "GET":
                if (req.url === "/") {
                    resp.end();
                }
                else if (req.url === "/employees") {
                    emp.getList(req, resp);
                }
                break;
            case "POST":
                break;
            case "PUT":
                break;
            case "DELETE":
                break;
            default:
                break;
        }

    }).listen(settings.webPort, function () {
        console.log("Server Started Listening at: " + settings.webPort);
    });

employees.js

var db = require("../core/db");

exports.getList = function (req, resp) {
    db.executeSql("SELECT * FROM EMPLOYEE", function (data, err) {
        if (err) {
            resp.writeHead(500, "Internal Error Occured", { "Content-Type": "text/html" });
            resp.write("<html><head><title>500</title></head><body500: Internal Error. Details: " + err + "></body></html>");
        }
        else {
            resp.writeHead(200, {"Content-Type": "application/json"});
            resp.write(JSON.stringify(data));
        }
        resp.end();
    });
};

exports.get = function (req, resp, empno) {

};

exports.add = function (req, resp, reqBody) {

};

exports.update = function (req, resp, reqBody) {

};

exports.delete = function (req, resp, reqBody) {

};

settings.js

exports.dbConfig = {
    user: 'sa',
    password: '123abc',
    server: 'localhost',
    database: 'LWWEBAPP',
    port: 1433
};

exports.webPort = 8080;



via joey.coyle