Saturday 6 May 2017

Client side routing using jQuery/JavaScript

I'm doing some experimenting in using pure JS/jQuery to handle client-side logic (rather than a framework, like Angular). The problem I'm running into right now is how to log a user in.

Here is my login.hbs file:

<div align="center">
<h2 class="page-header">Account Login</h2>
<form>
  <div class="form-group">
    
    <input type="text" class="form-control" name="username" placeholder="Username" style="width: 20%">
  </div>
  <div class="form-group">
    
    <input type="password" class="form-control" name="password" placeholder="Password" style="width: 20%">
  </div>
  <button type="button" class="btn btn-success" onclick="login()">Login</button>
</form>
</div>

This submit request goes to a JS file: login.js:

$(document).ready(function() {
    login = () => {     
        var username = $("[name='username']").val()
        var password = $("[name='password']").val()
        $.ajax({
            type: "PUT",
            url: '/login',
            data: {
                username: username,
                password: password
            },
            success: function(response) {
                console.log('Success:')
                console.log(response)
            },
            error: function(error) {
                console.log("Error:")
                console.log(error)
            }
        })
    }
})

On the server side, I'm accepting this PUT request in index.js:

router.put('/login', function(req, res) {
    // Password is not encrypted here
    console.log('req.body')
    console.log(req.body)

    User.findOne({ username: req.body.username }, function(err, user) {
        // Password is encrypted here
        if (err) throw err
        console.log('user')
        console.log(user)

        bcrypt.compare(req.body.password, user.password, function(err, result) {
            if (result) {
                var token = jwt.encode(user, JWT_SECRET)
                return res.status(200).send({ user: user, token: token })
            } else {
                return res.status(401).send({error: "Something is wrong."})
            }
        })
    })
})

The current flow is: a user enters their credentials, and those credentials get returned to the success method in my ajax request. The credentials show up in the browser's console (confirming that the server and client are communicating). The question is, how do I route this request to the profile page (or any other page, for that matter)? That is, the user is at http://localhost:3000/login, and after successfully logging in, they are routed to http://localhost:3000/profile, for example, where their personal profile information appears. I'd love to learn both ways of doing this type of routing (server-side and client-side). Thanks!



via Farid

Query MongoDb records from 5 days ago using '_id'

I've read online that '_id' holds a timestamp on when it was created and you are able to query it depending on a date. This is what I've I tried so far, but not having any luck.

var d = new Date();
d.setDate(d.getDate() - 5);

collection.find( { }, { metal: 1, change: 1, percent: 1, _id: { $gte: d } } ).toArray(function(err, results) {
    console.log(results);
});



via user992731

Socket.io mime mismatch error

Here is app.js file

import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import http from 'http';
import event from 'events';
import io from 'socket.io';
import session from 'express-session';
import passport from 'passport';
import LocalStrategy from 'passport-local';
import multer from 'multer';
import fs from 'fs';
import passportLocalMongoose from 'passport-local-mongoose';
import postRoutes from './server/routes/posts.routes';
import commentRoutes from './server/routes/comments.routes';
import authRoutes from './server/routes/auth.routes';
import userRoutes from './server/routes/users.routes';
import {passportConfig} from './server/config/passport.config';
import {socketFunction} from './server/config/socket.io.config';
import path from 'path';

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

const sanitizer = require('sanitize-html');
const app = express();

const server = http.Server(app);
const socket = io(server);
const localEvent = event.EventEmitter;
const myEvent = new localEvent();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,Access-Control-Allow-Origin, Content-Type, Accept, Authorization");
  res.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");

  next();
 });


app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(session({
  secret: "some secret",
  resave: false,
  saveUninitialized: false
}))

passportConfig(app);

app.use(postRoutes);
app.use(commentRoutes);
app.use(authRoutes);
app.use(userRoutes);
app.use(express.static(path.join(__dirname, '/client')))
app.use(express.static(path.join(__dirname, 'node_modules')))
app.use(express.static(path.join(__dirname, 'uploads')))


const port = 6655;

['/admin/', '/admin/:var', '/admin/edit/:var'].forEach(function(url){
  app.get(url, (req, res)=>{
    res.sendFile(path.join(__dirname, '/client', '/dashboard', '/index.html'));
  })
})

const blogRoutes = ['/', '/articles', '/articles/:url', '/contact'];

blogRoutes.forEach(el=>{
  app.get(el, (req, res)=>{
    if(el === '/articles/:url'){
      socketFunction(socket, req.params.url, myEvent)
    }
    res.sendFile(path.join(__dirname, '/client', '/blog', '/blog.html')); 
  })
})

app.listen(process.env.PORT, process.env.IP, ()=>{
  console.log(`Express server listening on port ${process.env.PORT} and IP ${process.env.IP}`);
});

Here is my socket.io.config file

function socketFunction(io, url, event){
    const blog = io.of(`/articles/${url}`)
    const admin = io.of('/admin/home')
    blog.on('connection', (fromBlog)=>{
        console.log("Connection made on blog");
        fromBlog.on('comment', (msg)=>{
            event.emit('comment-posted', {
                msg: msg.message
            })
        })
    })
    admin.on('connection', (toAdmin)=>{
        console.log("Connection made on admin");        
        event.on('comment-posted', (msg)=>{
            toAdmin.emit('blog-comment', {
                msg: msg.message
            })
        })
    })
}

export {socketFunction}

and here are my two html files

<!DOCTYPE html>
<html ng-app="blog">
  <head>
    <meta charset="utf-8">
    <base href="/blog" target="_blank">
    <title>Ayush Bahuguna | Web Developer</title>
    <link rel="stylesheet" href="/blog/dist/css/styles.css">
  </head>
  <body>
    <script src='/socket.io/socket.io.js' type="text/javascript" charset="utf-8"></script>
    <script src="/blog/dist/js/vendor.js" charset="utf-8"></script>
    <script src="/blog/dist/js/app.js" charset="utf-8"></script>
  </body>
</html>

<!DOCTYPE html>
<html ng-app="cms">
  <head>
    <meta charset="utf-8">
    <base href="/admin">
    <title>Blog Admin | Ayush Bahuguna</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
  </head>
  <body>
  <root></root>
  <script src="/socket.io/socket.io.js"></script>
  <script src="/dashboard/dist/plugins/tinymce/tinymce.min.js" charset="utf-8"></script>
  <script src="/dashboard/dist/js/vendor.js"></script>
  <script src="/angular-ui-tinymce/dist/tinymce.min.js" charset="utf-8"></script>
  <script src="/dashboard/dist/js/app.js"></script>
  </body>
</html>

I am receiving The resource from “http://localhost:6655/socket.io/socket.io.js” was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

I checked the network tab, and the type on the socket.io.js file is set to text/html. I don't know why is this issue occurring, I don't have any catch all routes.

I tried to find a way around, by using the socket.io.js available in the client folder of the socket.io, but turns out that socket.io is not looking for that file and is explicitly looking for /socket.io/socket.io.js

Your help is very much appreciated.



via Ayush Bahuguna

NodeJS REST turkish character, Socket hang up

My REST service is the following:

const
  express = require('express'),
  app = express();
  
  ...
  
 app.get('/turkish-escape/:id', function(req, res) {
  console.log("converting turkish special characters:");
  console.log("\u011f \u011e \u0131 \u0130 \u00f6 \u00d6 \u00fc \u00dc \u015f \u015e \u00e7 \u00c7");
  let char = req.params.id;
  
 .....//DO stuff

When I try to GET the service in the Browser I don't get any errors: http://localhost:8081/turkish-escape/ğ/

When I try to get the result with my REST Client I encounter some problems with some turkish special characters.

Client code:

let currentChar = text[i];
  let
    request = require('request'),
    options = {
      method: 'GET',
      url: 'http://localhost:8081/turkish-escape/' + currentChar + "/"
    };
    request(options, function(err, res, body) {
      if(err) {
        throw Error(err);
      } else {
        body = JSON.parse(body);
        console.log(body.convertedChar);
        newText += body.convertedChar;
      }
    });

When I call the client with an 'ü' it works fine, but if I call it with an 'ğ' it crashes. This is the call and Stack Trace:

./turkishTextConverter.js ğ
/pathtofile/turkishTextConverter.js:25
    throw Error(err);
    ^

Error: Error: socket hang up
at Request._callback (/pathtofile/turkishTextConverter.js:25:15)
at self.callback (/pathtofile/node_modules/request/request.js:188:22)
at emitOne (events.js:96:13)
at Request.emit (events.js:191:7)
at Request.onRequestError (/pathtofile/node_modules/request/request.js:884:8)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:191:7)
at Socket.socketOnEnd (_http_client.js:394:9)
at emitNone (events.js:91:20)
at Socket.emit (events.js:188:7)

As you see from the stack it never reaches even the first console.log statement of the REST Service



via nufuk

issues with error messages while validating the form field in express js

In case of any validation errors I want to display appropriate error message in the same jade page(i.e register.jade).If not then I want to store the data with the help of schema object succesfully and return to my home page. But currently, I am getting all the error messages even though the inputs are correct.

I am using Express+Node+Mongodb+Mongoose.

May I know how to achieve it.

Relevant (12:55 min) video which i am following is - https://www.youtube.com/watch?v=jeiP4jN1mfs&list=PLNiY_2deiFolObKp8sav6TmxnnjVFuwqu&index=16

Here is my code -

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session=require('express-session');
var passport=require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');

var multer = require('multer');

var upload = multer({ dest: './uploads' });
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;

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

var app = express();

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


// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

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

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

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

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


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

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

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

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

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

module.exports = app;


users.js(inside routes folder)

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


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

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

router.post('/register',function(req,res,next){
    //Get form values
    var name=req.body.name;
    var email=req.body.email;
    var username=req.body.username;
    var password=req.body.password;
    var password2=req.body.password2;



    if(req.files && req.files.profileimage){
        console.log('Uploading FIle...');

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

    //Form Validation

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

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

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

        });

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

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

        res.location('/');
        res.redirect('/');
    }
});
module.exports = router;


register.jade inside views folder

extends layout

block content
    h1 Register
    p Please Register using the form below
    ul.errors
        if errors
            each error, i in errors
                li.alert.alert-danger #{error.msg}
    form(method='post',action='/users/register',enctype='multipart/form-data')
        .form-group
            label Name
            input.form-control(name='name', type='text',placeholder='Enter Name')
        .form-group
            label Email
            input.form-control(name='email', type='email',placeholder='Enter Email')
        .form-group
            label Username
            input.form-control(name='username', type='text',placeholder='User Name')
        .form-group
            label Password
            input.form-control(name='password', type='password',placeholder='Enter Password')
        .form-group
            label Confirm Password
            input.form-control(name='password2', type='password',placeholder='Confirm Password')
        .form-group
            label Profile Image
            input.form-control(name='profileimage', type='file')
        input.btn.btn-default(name='submit',type='submit',value='Register')



via Suraj

Angular argument assigning issue

I am trying an app in MEAN stack. I have created a contact list for add. edit, update,delete operation using MEAN. When I am trying to get all contacts from my Contact model I am getting the below errors in my code.

Kindly my code below.

import { Component, OnInit } from '@angular/core';
import {ContactService} from '../contact.service';
import {Contact} from '../contact';

@Component({
  selector: 'app-contacts',
  templateUrl: './contacts.component.html',
  styleUrls: ['./contacts.component.css'],
  providers: [ContactService]
})
export class ContactsComponent implements OnInit {
  contacts: Contact[];
  contact:Contact;
  first_name:string;
  last_name:string;
  phone:string;

  constructor(private contactService: ContactService) { }

  ngOnInit() {
        this.contactService.getContacts()
      .subscribe( contacts->this.contacts = contacts);
  }

}

I got the below errors when I run my application

ERROR in /var/www/html/contactlist/client/src/app/contacts/contacts.component.ts (22,28): Expression expected.

ERROR in /var/www/html/contactlist/client/src/app/contacts/contacts.component.ts (22,43): ',' expected.

ERROR in /var/www/html/contactlist/client/src/app/contacts/contacts.component.ts (22,19): Cannot find name 'contacts'. Did you mean the instance member 'this.contacts'?

ERROR in /var/www/html/contactlist/client/src/app/contacts/contacts.component.ts (22,19): Argument of type 'boolean' is not assignable to parameter of type '(value: any) => void'.

ERROR in /var/www/html/contactlist/client/src/app/contacts/contacts.component.ts (22,19): Operator '>' cannot be applied to types 'number' and 'Contact[]'.

ERROR in /var/www/html/contactlist/client/src/app/contacts/contacts.component.ts (22,45): Cannot find name 'contacts'. Did you mean the instance member 'this.contacts'?

ERROR in ./src/app/contacts/contacts.component.ts
Module parse failed: /var/www/html/contactlist/client/node_modules/@ngtools/webpack/src/index.js!/var/www/html/contactlist/client/src/app/contacts/contacts.component.ts Unexpected token (18:35)
You may need an appropriate loader to handle this file type.
|     ContactsComponent.prototype.ngOnInit = function () {
|         this.contactService.getContacts()
|             .subscribe(contacts -  > this.contacts, contacts);
|     };
|     return ContactsComponent;
 @ ./src/app/app.module.ts 12:0-66
 @ ./src/main.ts
 @ multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts



via rsvijay

MEAN application link redirection

I've setup a system where a user can login to a website I created with a MEAN application. It's a two step setup. The user registers an account and is then emailed a link where it redirects them to a "http://localhost:3000/users/verify?email=". My problem is when the user clicks the link, it redirects them to here in the server file called app.js

app.get('*', function(req, res){
  res.redirect('/');
});

As opposed to redirecting them to

router.post('/verify', function(req, res){

In the /users.js file.

I know it doesn't sound the clearest, but I can further explain my problem if that helps. Any help is appreciated!



via A. Angee

How to Parse a JSON response and group them date wise and head wise into a table in javascript?

This is the Sample response i am getting from the API.

{"success":true,"transaction":[{"_id":"58efd5717ddda769f26793fc","transId":"Exp/04-17/17","trpId":"Trav/dfsd/04-17/12","tripId":"58efd4dc7ddda769f26793f8","userId":"58ac19eaec1e7e4628be6f01","expenseHeadId":"588f279b85cd494eb7989c83","expenseHeadName":"Conveyance Expenses","transactionAmount":799,"isReimbursible":true,"paymentMode":"Cash","travelPurpose":"Official","hodId":"58aac3cb35c7194023da4777","clientId":"588f279b85cd494eb7989c80","fromCity":"Delhi","toCity":"Bhilai","fromCityId":"57f4aae6c0cd6b4cde54a514","toCityId":"583e0303e69a2e27ed7b416d","tripEndDate":"2017-04-27T18:30:00.000Z","policyDescription":"Not Applicable","expenseType":"general","__v":0,"hodApprovedTime":"2017-04-13T19:46:21.585Z","adminApprovedTime":"2017-04-13T19:47:55.910Z","accountsApprovedTime":"2017-04-13T20:07:30.097Z","paymentId":["58efda82f38d502c9e7fc5c1"],"isAccountsPaid":true,"isCancelled":false,"transactionStatus":"accounts-approved","isAccountsApproved":true,"isAdminApproved":true,"isHodApproved":true,"isDocUploaded":false,"createdTime":"2017-04-13T19:45:53.672Z"},{"_id":"58efd87af38d502c9e7fc5ba","transId":"Exp/04-17/18","trpId":"Trav/dfsd/04-17/12","tripId":"58efd4dc7ddda769f26793f8","userId":"58ac19eaec1e7e4628be6f01","expenseHeadId":"588f279b85cd494eb7989c85","expenseHeadName":"Travel","transactionAmount":1231,"isReimbursible":true,"paymentMode":"Draft","travelPurpose":"Official","hodId":"58aac3cb35c7194023da4777","clientId":"588f279b85cd494eb7989c80","fromCity":"Delhi","toCity":"Bhilai","fromCityId":"57f4aae6c0cd6b4cde54a514","toCityId":"583e0303e69a2e27ed7b416d","tripEndDate":"2017-04-27T18:30:00.000Z","policyDescription":"Not Applicable","expenseType":"general","__v":0,"hodApprovedTime":"2017-04-13T20:00:36.469Z","adminApprovedTime":"2017-04-13T20:00:53.898Z","accountsApprovedTime":"2017-04-13T20:03:39.801Z","paymentId":["58efd99bf38d502c9e7fc5bf"],"isAccountsPaid":true,"isCancelled":false,"transactionStatus":"accounts-approved","isAccountsApproved":true,"isAdminApproved":true,"isHodApproved":true,"isDocUploaded":false,"createdTime":"2017-04-13T19:58:50.678Z"}]}

What i a struggling in is how to display the data on the angular page as a table in which the row heads are the Dates and the Column Heads are the "expenseHeadName" in the response.

I have tried using a lot of different techniques nested loops and so on but so far nothing has worked satisfactorily.

For Example i would want table like this:

DATE        TRAVEL     FOOD   LODGING   TOTAL
15 Jun-2017    250       300     400       950
17 June 2017   300       200       0       500

My code till now (not sure if that will help)

angular.forEach(response, function (value, key) {

        var obj={};
       //var d=new Date(value.createdTime);


       // var d =value.createdTime;
        var d =new Date(value.createdTime);
         var d5 =d.setHours(0,0,0,0);
        var d6=new Date(d5);
         angular.forEach(response, function (value1, key1) {
             var d1=value1.createdTime;
             var d1 = new Date(d1);
            var d2 =d1.setHours(0,0,0,0);
             var d3=new Date(d2);
            if (d6.getTime() == d3.getTime()) 
            {
                obj['date']=d3;

                 angular.forEach(expenseHeadsArray, function (value, key) 
                        {
                            obj[value.expenseHeadName] = 0;

                        });
                obj['total']=0;
                rows.push(obj);

            }                 

         });
      // obj['date']=d.toDateString();

    });



    angular.forEach(rows, function (value_rows, key_rows) {
        angular.forEach(response, function (value_resp, key_resp) {
            var d1 = new Date(value_rows.date);
            var d2 = new Date(value_resp.createdTime);
            var d3 =d2.setHours(0,0,0,0);
            var d4=new Date(d3);
           // if (angular.equals(value_rows.date, value_resp.createdTime)) {
             if (d1.getTime() == d4.getTime()) {
                angular.forEach(expenseHeadsArray, function (value_expenseHead, key_expenseHead) {
                    if (angular.equals(value_resp.expenseHeadName, value_expenseHead.expenseHeadName)) {
                        var exhead=value_expenseHead.expenseHeadName;

                        rows[key_rows][exhead] += value_resp.transactionAmount;
                        rows[key_rows].total += value_resp.transactionAmount;
                }

                });
            }
        });
    });

Maybe i am missing out some easy link but any help would be appreciated.

I am using Angular .js on the frontend and Node.js on the backend



via Vaibhav Singh

How do I refresh a Refresh Token

Sorry for the simple question I just keep finding examples of "how to use them" not "when to use them"

Basically I have the code done for creating the refreshToken and destroying it

// Compare token in the database and create a new access token
Player.prototype.validateRefreshToken = function(username, refreshToken) {
    return new Promise(async (resolve, reject) => {
        try {
            let player = await this.col.findOneAsync({ username, refreshToken});
            if (player) {
                let token = jwt.sign(
                    {
                        id: player._id,
                        username: player.username, 
                        email: player.email,
                        roles: player.role || "user"
                    }, 
                    globals.jwtSecret,
                    {
                        expiresIn: "300"
                    }
                );

                return resolve(token);
            } else {
                return resolve(null);
            }
        } catch(err) {
            console.log("[ERROR]: There was an error trying to validateRefreshToken");
            console.log(err);
            return reject(err);
        }
    });
}

// Destroy users refreshToken by generating a new one and not delivering
// it to the client
Player.prototype.rejectToken = function (refreshToken) {
    return new Promise(async (resolve, reject) => {
        try {
            let player = await this.col.findOneAndUpdateAsync(
                { refreshToken },
                { $set: { refreshToken: randtoken.uid(256) },
            });
            if (player) {
                return resolve(true);
            } else {
                return resolve(false);
            }
        } catch(err) {
            console.log("[ERROR]: There was an error trying to rejectToken");
            console.log(err);
            return reject(err);
        }
    });
}

// API Routes
// Check Refresh Token
router.post("/token", async (ctx, next) => {
    let username = _.get(ctx.request.body, "username");
    let refreshToken = _.get(ctx.request.body, "refreshToken");

    if (refreshToken) {
        try {
            let token = ctx.models.player.validateRefreshToken(username, refreshToken);
            if (token) {
                ctx.body = { success: true, token };
            } else {
                ctx.body = { success: false, errors: ["You need to reauthenticate yourself their was an issue getting your refresh token"] };
            }
        } catch(err) {
            console.log(err);
            ctx.body = { success: false, errors: ["Internal Server Error"] };
        }
    } else {
        ctx.body = { success: false, errors: ["You are not authenticated"] };
    }
});


// Destroy refresh token
router.post("/token/reject", async (ctx, next) => {
    let refreshToken = _.get(ctx.request.body, "refreshToken");
    if (refreshToken) {
        try {
            let result = await ctx.models.player.rejectToken(refreshToken);
            if (result) {
                ctx.body = { success: true };
            } else {
                ctx.body = { success: false, errors: ["You are not authenticated"] };
            }
        } catch(err) {
            console.log(err);
            ctx.body = { success: false, errors: ["Internal Server Error"] };
        }
    }
});

But my problem is I don't know when I'm supposed to post to /token

E.g. somebody does a post request to their own profile /profile/me but gets a permission error, now what, how do I automate the /token

I hope this makes sense if it doesn't ask me for clarification



via Datsik

Get Notified when someone comments on a video from youtube

I want to perform analytics when anyone comments on a video from a certain channel .Is there a way to get notified through the Youtube Data Api or the Youtube Analytics Api. I am using a nodejs server.



via uman

Chaining functions

I am currently trying to use the got module https://www.npmjs.com/package/got but I am a bit confused on the format/order of functions. It's evident that you can chain the listeners and functions as such

 got.stream(link)
 .on('response', resp => {
   if (resp.statusCode != 200) this.emit('error', '!200')
 })
 .on('error', err => {
   console.log(err)
 })
 .pipe(somewhere)

The request module also does this. But how do you avoid .pipe if you want it to happen only on the condition resp.statusCode != 200? Seeing that it's used in a lot of request modules, it must be a very basic thing to understand but I can't quite grasp it.



via platizin

TypeError: sql.Connection is not a function Node.js

I am very beginner with node.js and javscript itself. I am trying to establish a basic connection to SQLServer but I am getting the following error:

TypeError: sql.Connection is not a function

I am following the recommendations of the mssql package git repository

//get an instance of sqlserver 
var sql = require('mssql');

//set up a sql server credentials
var config = {
server: 'localhost',
database: 'trafiyadb',
user: 'jhonycage',
password:  'juan1014',
port: 1433
};


function con() {
var dbConn = new sql.Connection(config);
dbConn.connect().then(function(){
    console.log("connected")
}).catch(function (err) {
    console.log(err);
})
}

con();

and this is the package.json

{
 "name": "trafiyaapi",
 "version": "1.0.0",
 "description": "",
 "main": "server.js\u001b[A\u001b[B\u001b[B\u001b[B\u001b[A\u001b[B",
 "dependencies": {
 "express": "^4.15.2",
 "body-parser": "^1.17.1",
 "mssql": "^4.0.4",
 "jsonwebtoken": "^7.4.0"
 },
 "devDependencies": {},
 "scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
 "start": "node server.js"
 },
 "author": "",
 "license": "ISC"
 }

I am just executing

$node server

I must be doing something wrong, how can i connect to database?



via Juanca

Using leaflet within create-react-app in node.js

I am a novice programmer trying to incorporate leaflet through create-react-app for a project. With very little background in node.js I have run into several issues. I believe I have installed leaflet properly through node.js and have done the following to implement my code in the "app.js" file:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
var axios = require("axios")
var leaflet = require("leaflet")
var map = leaflet.map('map');
map.setView([47.63, -122.32], 11);
class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <div id = 'map'></div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

The output to the local host after this is run is a blank page. Considering I have little experience in this domain, I was wondering if I was headed down the right track, or if anyone has suggestions for a fix.

Thank you



via Taylor Rohrich

How to pass data from connect route to Meteor

I am adding an auth layer and I think I have it figured out except for one tricky detail. My Meteor app doesn't have any routes but I've added a hook into the connect middleware so that the "/" route errors if there isn't a correct API token. If the token is okay then I call next() to forward the route to Meteor.

The problem is that, depending on the token, I need to set server-side parameters for the connection, and I don't know how to do this. For example, say I have a static list of API keys mapped to permission levels. If a user sends a request with "ADMIN_API_KEY" then I would like to set Session.permission_level = "admin" for use by the Meteor server's functions. Session is just for the client in Meteor, though.

  # this code's in coffeescript

  WebApp.connectHandlers.use '/', (req, res, next) ->
    validator = new RequestValidator(req, next)
    validations = [
      "valid_namespace",
      "only_https"
    ]
    error = validator.validate(validations)
    next(error)
    # <<<<<<<<<<<<<<<<<<<<<<<<
    # Here I want to set some config option which can be
    # read by the server in the same way it can read things like
    # Meteor.user()

In Rails I would just say session[:permission_level] = "admin". But it seems to not work this way in Meteor.

By the way, I am not using a Routing package yet in Meteor, though if that would make this easier than I would.



via maxple

Trouble with express routing

Hello I am fairly new to node, I having trouble with routing in an express app. I have looked at documentation and searched for answers, tried a little bebugging but no luck. here is current code on github https://github.com/Ongomobile/my-api

I am using express router to route from 2 files in my routes directory, the index route works fine but the end points in routes/products.js do not work with app.use(), they do work if I use app.get() or if I put end points in routes/index.js

In my server.js file (I believe my problem is in code below)

var indexRoutes   = require('./routes/index'),
productRoute = require(‘./routes/products’)

app.use('/', indexRoutes);
app.use('/product', productRoute);

Routes/products.js
var express = require('express');
var router = express.Router();
var Product = require('../model/product');
router.get('/product', function(req, res) {
    Product.find({}, function(err, products) {

        if(err) {
            res.status(500).send({error: "Products not found..."});
        }else {
            // res.send(products);
            res.send("<h1>Products will show here when populated</h1>");
        }
    });
});

router.post('/product', function(request, response) {
 …….
  });

module.exports = router;



via Mike Haslam

Javascript: Decode String from File?

I am trying to decode a string from a file like this:

decode(fs.readFile(path.join(inbox.dir, inbox.messages[found].lastHash), 'utf8'))

But this is my output: �w^~)�



via grant

Node.js Filename invalid encoding characters

When writing a new file and the filename contain unicode characters with this code:

fs.writeFile('êèñéß™.txt', 'hello')

the filename in the filesystem returns something along the lines like this:

����ï¿.txt

Is there a way to specify the filename encoding?



via makkesk8

downloading a large file with nodejs and my process is hanging

I have a function that downloads a file from an ftp directory with credentials. All the log messages fire as expected but my process never closes. The zip file is about a gigabyte.

Here is the function

var pullZip = function (file_url, username, password, file_name) {

  logger.info('Starting to request zip from: ', file_url);

  var deferred = Q.defer();

  var ws = fs.createWriteStream(__dirname + file_name);

  ws.on('error', function(err) { 
      logger.error(err);
      deferred.reject(err);
  });

  var zipRequest = request({
      url: file_url
      , encoding: null
      , auth: {
          username: username
          , password: password
      }
  });

  zipRequest.on('error', function(err) {
      logger.error(err);
      deferred.reject(err);
  });

  zipRequest.on('response', function(response) {

      logger.info('Response status was ' + response.statusCode);
      logger.info('Started downloading zipfile.');

      response.pipe(ws).on('finish', function() {
        logger.info('Finished writestream.');
        ws.close(function(){
              logger.info('Closing write stream.');
              deferred.resolve();
          });  // close() is async, call cb after close completes.
      });

  });

  return deferred.promise;
};

var pullZipDeferred = pullZip('https://mylocation/dir/file1.zip', 'user', 'pass', 'file1.zip').then(function(response){
    logger.info('done.');
}, function(reason){
    logger.info('done. but with problems.');
});

console spits out

2017-05-07T02:31:11.438Z - info: Starting to request zip from:  https://mylocation/dir/file1.zip
2017-05-07T02:31:12.011Z - info: Response status was 200
2017-05-07T02:33:21.917Z - info: Finished writestream.
2017-05-07T02:33:21.929Z - info: Closing write stream.
2017-05-07T02:33:21.931Z - info: done.

.. the process never exits (I'm not sure how to figure out what's still open) .. and the file1.zip is of 0 bytes.

Any ideas on how to track this one down?



via Kirby

Cannot run npm run build or npm start

Whenever I try building my web-pack file or starting web-pack dev server I get an error. It was working, but I was messing around with eslint and broke something.

This is the error package when trying npm build

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'run', 'build' ]
2 info using npm@4.5.0
3 info using node@v6.10.3
4 verbose run-script [ 'prebuild', 'build', 'postbuild' ]
5 info lifecycle setup@1.0.0~prebuild: setup@1.0.0
6 silly lifecycle setup@1.0.0~prebuild: no script for prebuild, continuing
7 info lifecycle setup@1.0.0~build: setup@1.0.0
8 verbose lifecycle setup@1.0.0~build: unsafe-perm in lifecycle true
9 verbose lifecycle setup@1.0.0~build: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/Users/Nims/Documents/Web Development/Projects/React bookstore/node_modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
10 verbose lifecycle setup@1.0.0~build: CWD: /Users/Nims/Documents/Web Development/Projects/React bookstore
11 silly lifecycle setup@1.0.0~build: Args: [ '-c', 'webpack' ]
12 silly lifecycle setup@1.0.0~build: Returned: code: 1  signal: null
13 info lifecycle setup@1.0.0~build: Failed to exec build script
14 verbose stack Error: setup@1.0.0 build: `webpack`
14 verbose stack Exit status 1
14 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:279:16)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at EventEmitter.emit (events.js:191:7)
14 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/spawn.js:40:14)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at ChildProcess.emit (events.js:191:7)
14 verbose stack     at maybeClose (internal/child_process.js:886:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid setup@1.0.0
16 verbose cwd /Users/Nims/Documents/Web Development/Projects/React bookstore
17 verbose Darwin 16.5.0
18 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "build"
19 verbose node v6.10.3
20 verbose npm  v4.5.0
21 error code ELIFECYCLE
22 error errno 1
23 error setup@1.0.0 build: `webpack`
23 error Exit status 1
24 error Failed at the setup@1.0.0 build script 'webpack'.
24 error Make sure you have the latest version of node.js and npm installed.
24 error If you do, this is most likely a problem with the setup package,
24 error not with npm itself.
24 error Tell the author that this fails on your system:
24 error     webpack
24 error You can get information on how to open an issue for this project with:
24 error     npm bugs setup
24 error Or if that isn't available, you can get their info via:
24 error     npm owner ls setup
24 error There is likely additional logging output above.
25 verbose exit [ 1, true ]

and when trying npm start

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'start' ]
2 info using npm@4.5.0
3 info using node@v6.10.3
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle setup@1.0.0~prestart: setup@1.0.0
6 silly lifecycle setup@1.0.0~prestart: no script for prestart, continuing
7 info lifecycle setup@1.0.0~start: setup@1.0.0
8 verbose lifecycle setup@1.0.0~start: unsafe-perm in lifecycle true
9 verbose lifecycle setup@1.0.0~start: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/Users/Nims/Documents/Web Development/Projects/React bookstore/node_modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
10 verbose lifecycle setup@1.0.0~start: CWD: /Users/Nims/Documents/Web Development/Projects/React bookstore
11 silly lifecycle setup@1.0.0~start: Args: [ '-c', 'webpack-dev-server' ]
12 silly lifecycle setup@1.0.0~start: Returned: code: 1  signal: null
13 info lifecycle setup@1.0.0~start: Failed to exec start script
14 verbose stack Error: setup@1.0.0 start: `webpack-dev-server`
14 verbose stack Exit status 1
14 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:279:16)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at EventEmitter.emit (events.js:191:7)
14 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/spawn.js:40:14)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at ChildProcess.emit (events.js:191:7)
14 verbose stack     at maybeClose (internal/child_process.js:886:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid setup@1.0.0
16 verbose cwd /Users/Nims/Documents/Web Development/Projects/React bookstore
17 verbose Darwin 16.5.0
18 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
19 verbose node v6.10.3
20 verbose npm  v4.5.0
21 error code ELIFECYCLE
22 error errno 1
23 error setup@1.0.0 start: `webpack-dev-server`
23 error Exit status 1
24 error Failed at the setup@1.0.0 start script 'webpack-dev-server'.
24 error Make sure you have the latest version of node.js and npm installed.
24 error If you do, this is most likely a problem with the setup package,
24 error not with npm itself.
24 error Tell the author that this fails on your system:
24 error     webpack-dev-server
24 error You can get information on how to open an issue for this project with:
24 error     npm bugs setup
24 error Or if that isn't available, you can get their info via:
24 error     npm owner ls setup
24 error There is likely additional logging output above.
25 verbose exit [ 1, true ]

It seems its not picking up the local scripts in my webpack.config.js file - but I'm new to this and I'm still learning



via Nims

Sending POST request to a Drupal module file

I'm trying to send a post request to a Drupal .module file from node.js. My problem is that the module file is never executed as php by Apache when the request is made, so instead of getting a response from php, I get the literal code (inside the .module file) as a text string.

I tried enabling .module to execute as php (not sure the security implications) by putting the following in .htaccess:

Addhandler application/x-httpd-php .module

(and virtually every other combination of that command I could find)

But no luck.

I know the post request sent by node.js is perfectly fine because it works when sent to .php files on the same server. I just can't get it to work within a Drupal module. I want it to be sent to a Drupal module because I want to take advantage of Drupal's API (going to be doing a lot of modifications to drupal user tables).

How do I send a post request to a drupal module, programmatically, from node and read its response? I know how to send it to a simple .php file, but not to a drupal module.



via Chris Scott

how to plan for scaling-architecture of a single-droplet Digital Ocean app

I'm about to launch a nodejs-mongodb app on a Digital Ocean (DO) single droplet. I'm here to make sure if I'm reasoning correctly on how to add droplets in future for scaling against load, if any.

I'm going to:

  1. setup Nginx, MongoDB, Nodejs app, all on a single droplet of DO.
  2. create an image of the app into DockerHub, further launch app from the droplet and wait until it brings load.
  3. Then create a Rancher network with Nginx and app-hosting droplets,
  4. finally, switch off the Nginx and app from the initial droplet, replace it by the Rancher network app-hosts. The initial droplet will be First MongoDb droplet-server.
  5. further, when necessary, to add MongoDB droplets and sharding to have a cluster of MongoDB, to add app-hosting droplets in the Rancher network.

Please let me know if these steps are what I could rely to, or where else I should look.



via Adrian Dain

I get an error when I try to create scheduler job Node js

I get this error in console when I run a scheduler job in node js enter image description here

Even the job "eventQuestionnaireMail" run successfully.

scheduler 2017-05-07T01:06:19.903Z - [INFO] - Scheduler registered successfully'eventQuestionnaireMail' +6ms

This is the ts file event.ts:

    var __get3daysagoEvents = function ()
    {
    var today = __moment().utc().startOf("day").toDate();
    var ago3days = __moment().utc().subtract(8, 
  "days").startOf("day").toDate();
    //var ago3days = __moment().utc().subtract(1,"min");
    console.log('gggggggggggggggggggggggggg');
    console.log(JSON.stringify(today));
    console.log('gggggggggggggggggggggggggg');
    console.log('mmmmmmmmmmmmmmmmmmmmmmmmmm');
    console.log(JSON.stringify(ago3days));
    console.log('mmmmmmmmmmmmmmmmmmmmmmmmmmmm');
    var query =
        {
            attributes: ["id", "name", "themeId", "goalId", 
   "startDate", "endDate", "status", "userId", "attendees"],
            where: {
                endDate: {
                    $gte: ago3days,
                    $lt: today
                },
                //status: "BOOKED"
            }
        };

    return __eventDao.findAll(query);
    console.log('XXXXXXXXXXXXXXXXXXXXXXXXXXX');
    console.log(JSON.stringify(query));
    console.log('XXXXXXXXXXXXXXXXXXXXXXXXXXX');
    };

    var __sendQuestionnaireMail = async function(user, eventId)
    {
    // Send questionnaire email

    var emailParams =
        [
            {
                name: "ClientName",
                content: user.firstName + " " + user.lastName
            },
            {
                name: "ClientId",
                content: user.companyId

            }
        ];

    var templateName = 
    yemp.server.utilities.mailUtil.getQualifiedTemplateName(
        "client-questionnaire");

    var recipients = [];
    recipients.push({
        email: user.email,
        role: "CLIENT"
    });

    let info = await __notificationService.notifyByEmail(templateName, 
    null, emailParams, recipients);
    console.log('lllllllllllllllllllllllllllllllllllllllllll');
    console.log(JSON.stringify(emailParams, recipients));
    console.log('llllllllllllllllllllllllllllllllllllllllllll');
    };

     this.sendMailfor3DaysAgoEvents = function ()
     {
      __get3daysagoEvents().then(function (events , user)
     {
        if (Array.isArray(events) === false)
        {
            return;
            console.log('000000000000000000000000000000000000000');
            console.log(events);

            console.log('000000000000000000000000000000000000000');
            console.log(JSON.stringify(events));

            console.log('000000000000000000000000000000000000000');


        }
        for (let event of events)
        {

    console.log('vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv');

    console.log('vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv');

     console.log('vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv');

            __sendQuestionnaireMail(user, event.id).then(function ()
            {
                console.log('22222222222222222222222222222222222');
                console.log('22222222222222222222222222222222222');

                yemp.server.log.info(this,
                    "client questionnaire has been sent for the event 
      [" + event.id + "]");
            }).catch(function (error)
            {
                yemp.server.log.error(this, error);

      console.log('????????????????????????????????????????????');

      console.log('????????????????????????????????????????????');

             });
            }
          ;
        });
         };

This is the eventQuestionnaireMail.ts:

   "use strict";

    exports.class = function ()
    {
   var __schedule = require("node-schedule");
   var __configurationService = yemp.server.services.configuration;
   let __eventService = yemp.server.services.event;

   this.start = function ()
    {
    var emailQuestionnaireSchedulerRule = 




    __configurationService.getApplicationConfiguration("email 
     QuestionnaireSchedulerRule");
    __schedule.scheduleJob(emailQuestionnaireSchedulerRule, function 
    ()
     {
        yemp.server.log.debug("Background: Sending a client 
      questionnaire after 3 days of event starting day");
        __eventService.sendMailfor3DaysAgoEvents();
     });
     }
     };



via Afef Mokhtari

NodeJs and Dotenv - Running nodemon does not find .env file in src folder

I've got a pretty standard Nodejs setup using dotenv with my server.js file sitting in an src folder, a .env file sitting right next to it, along with a bin/www.js file. Ever since I started using dotenv, running all of the following no longer work... nodemon (from the root of my repo) npm start nodemon src/server nodemon src etc

All fail and none of my environment variables get loaded properly. I have to go to the actual src folder and run "nodemon server.js" at that exact location. This poses problems for some of the build environments I used to use and some of my previous cloud setups like heroku. I thought having the .env file in the same folder as my server.js file would always work, but it does not.

Can anyone tell me why dotenv fails to find the .env file and load the environment variables depending on where I launch nodemon from, even though nodemon finds the server.js file just fine?

I basically would like to be able to launch nodemon from my repository's root folder and still have dotenv work. Also, I tried moving the .env folder into the root directory, and I still have problems.



via Tim Hardy

async parallel callback is not defined

I am getting the error "callback is not defined" when trying to use async.parallel and but I am out of leads as to why. All the examples of async.parallel have the functions inline (like the async doco https://caolan.github.io/async/docs.html#parallel) but as the functions I want to run have some logic in them I have tried to split them out so they are not inline. This might be my problem but I think it should be possible, I just cannot figure out from the examples how the call backs should work in this situation.

Then intention here is to have two functions go get lists of IDs from different locations then put them together and do some things on the resulting array. I have trimmed the "go do other things" as it seems irrelevant at this stage.

var structuresIDArray = [];

function getPublicStructures(callback){
    request({
        url: 'https://esi.tech.ccp.is/latest/universe/structures/?datasource=tranquility',
        method: 'GET'
    }, function (error, response, body) {
        if(!error && !body.error && response.statusCode === 200){
            console.log('getting public locations');
            structuresIDArray.concat(JSON.parse(body));
            callback(null, structuresIDArray);
        }else{
            callback(error);
        }
    });
}

function getAssetLocationList(callback){
    db.any('select distinct "location_id" from "public"."charassets" where "location_id" is not null')
    .then(function (data) {
        for (var i = 0; i < data.length; i++) {
            structuresIDArray.push(data[i].location_id);
            if(i+1===data.length){
                callback(null, structuresIDArray);
            }
        }

    })
    .catch(function (err) {
        callback(err);
    });
}



function main(){

    async.parallel([ getAssetLocationList(callback), getPublicStructures(callback) ],
        function (err, results) {
            if (err) {
                throw err;
            }
            // Go do some other stuff now ...
        });
}



via So Bad

How to get telegram channel & group & bot members count by bot

I want get channel, group, bot members count by my bot with node js. somebody can help?



via davidtt

Do I need to use Node.js for my web app?

I want to make a web app that allows users to pick two genres and have the app play a song that fits a combination of those two genres. So for example, if a user were to pick hip-hop and rock as their genres then the app might play a song from the beastie boys. The app would look similar to moodfuse.com but instead of the user picking a choice of mood and genre they would just be choosing two genres. All songs are retrieved from youtube using the youtube api. Im really new to making web apps and web development in general but I really want to work on something big. My question is would i need to use something like node.js for my app? I know node.js is used when you want to have a persistent connection between a browser and server but i dont know it well enough to know if i need to use it here. I know it sounds stupid but i dont want to spend a lot of my time learning node.js until i know for a fact that it will be needed for my web app. Also, feel free to suggest any advice on my web app if you have any. Thanks.



via ad562

Send published Message to Browser or Clients interface one who subscribed to the channel NodeJS

How do I separate the code of publish and subscribe as Client.js and Server.js code? Also, how do I print the message on browser and not in console? Do I really need to use web sockets to push data to browser? like: Send message from Node.js Server to Client via function call

how do I pass it in routes:

router.get('/api', function(req, res, next) {
  res.render('index', { data: data });
}); 

app.js

var main = require("./server");

server.js

var http = require("http");
var fs = require("fs");
var PubNub = require("pubnub");
var connect = require("connect");

function server404Response (response) {
    response.writeHead(404,{'contentType':'text/plain'});
    response.write("404, Page Not Found Error");
    response.end();
}

function onRequest(request,response) {
    if(request.method == 'GET' && request.url == '/'){
        publish();
        response.writeHead(200,{'contentType':'text/html'});
        fs.createReadStream("./index.html").pipe(response);

    }else{
        server404Response(response);
    }
}

http.createServer(onRequest).listen(8888);
console.log("Server is running");   

function publish() {

    pubnub = new PubNub({
        publishKey : 'pub-key',
        subscribeKey : 'sub-key'
    })

    var publishConfig = {

        channel : "test",
        message : "Hello from PubNub Docs!"
    }

    pubnub.addListener({
        status: function(statusEvent) {

            if (statusEvent.category === "PNConnectedCategory") {
                pubnub.publish(publishConfig);
               }
        },
        message: function(message) {
            console.log("New Message!!", message);
        },
        presence: function(presenceEvent) {
            // handle presence
        }
    })
    //if I add subscribe code here. it just works fine
};

client.js

var PubNub = require("pubnub");

pubnub = new PubNub({
    publishKey : 'pub-key',
    subscribeKey : 'sub-key'
})

console.log("Subscribing..");
pubnub.subscribe({
    channels: ['test']
});



via Murlidhar Fichadia

Unhandled promise rejection on redirect in Nodejs

I have stumbled upon a strange issue with promises when redirecting in nodejs. In the code below I am using a function to handle writing to an object which will check if the item exists if it does it rejects, if it does not it resolves. When it resolves I am then redirecting the user to another page which contains the id used in the example in its url.

var Test = function() {

  var obj = {};

  function addItemToObj(id) {
    return new Promise(function(resolve, reject) {

      var idAlreadyExists = obj[id] ? true : false;

      if (idAlreadyExists) {
        return reject('id already exists');
      }

      obj[id] = 'test';
      return resolve(id);
    });
  }

  return {
    createTestPage: function(request, response) {

      var id = 'testid';

      return addItemToObj(id).then(function(id) {
        return response.redirect(`/newPage/${id}`);
      }).catch(function(error) {
        console.error(error);
      });
    }
  }
}

module.exports = new Test;

So when I run this code I get this error:

(node:46878) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot create property '_locals' on string 'Model already exists'

The error is saying that I am not handling the rejection, but I am in the catch. When I remove the redirect the error goes away, but I cannot find out why.

Can anyone shed any light on this issue?



via mmacartney

mongoose find and save not updating the document

I am using mongoose to find and modify and save back to the collection. Here is what I have tried:

if(req.body.writer){
     MyModel.find({writer: req.body.oldname},function (err, data) {
                for(var i = 0; i < data.length; i++){
                    data[i].writer= req.body.newName;
                    data[i].save()                    
                }
            });
}

why is this not updating the document? where is the problem lying? thanks



via cplus

Integrating Node Js and .Net Solution

We have a huge .Net application running on MVC. It has multiple projects under the main solution. We also have a replica of that application in Node js for front end developers. Off late - We have issues with developers working with two different solutions (Node and .Net) and keeping two copies of assets everywhere. We ultimately decided to combine them and bring the whole Node js application into our .Net Solution as 6th project.

Wondering if anyone has previously done so - integrating an a.Net application with existing Node js application. If so any pros and cons to consider. Also, would appreciate any links where I can see how to start merging these two applications.



via kveey

mongoose finds but doesn't remove

I am finding any document that matches my condition and I want to remove those docs.

MyModle.find({writer: req.body.id}, function(err, docs){
                if (err){ return console.log(err)}
                if (!docs || !Array.isArray(docs) || docs.length === 0){
                    return console.log('no docs found')}
                docs.forEach( function (doc) {
                    doc.remove();
                    console.log("Removed book with ID ",doc._id, "by writer ", req.body.id);
                });
            });

My console is printing the message as if the document was removed, but it is still in the collection. What is wrong here?



via cplus

Updating to a Mongo subdocument in node route

I have a simple schema, representing an Author, which holds a sub-document of books they've authored.

var bookSchema = new Schema ({
      title: {type: String},
      comments: [{type: String}]
});

var schema = new Schema ({
     fullName: {type: String, required: true, unique: true}, 
     bookList: [{bookSchema}]
});

When I attempt to add a new book (see below) to my author, the correct author is updated, with a new instance of a book. However, none of the values are added to the sub-document.

const length = req.body.bookList.length - 1;
const bookTitle = req.body.bookList[length];
console.log(bookTitle);
author.bookList.push({ title: bookTitle });

I believe the issue is related to the schema of my bookList not being visible, as it seems to always only add a new instance of the object, _id

  {
    "_id" : ObjectId("590e52dfe804ef4e74094faa"),
    "fullName" : "George Orwell",
    "bookList" : [
        {
            "_id" : ObjectId("590e52e9e804ef4e74094fab")
        },
        {
            "_id" : ObjectId("590e5475e804ef4e74094fac")
        }
    ],
    "__v" : 1
  }

Any advice/tips will be greatly appreciated, also please let me know if anything is unclear, still very new to this topic.

Thanks!



via Joshy Boy

Is it safe to protect NodeJS routes with Redis Store session variables?

I'm pretty new to MEAN stack applications and session flow itself. I have admin dashboard and certain API routes I want to protect to access only by an admin. Also I'm using socket.io with passport sessions stored in Redis Store and checking if user who emitted socket is authenticated and an admin. I'm granting admin rights in the following way: there is a MongoDB collection of users with certain boolean value "isAdmin".

When user authenticates we go:

db.users.findOne({ userID: profile.id }, function(err, user) {
    if (user) {
       // blah-blah-blah
       returnSession(user.isAdmin);
    }
});

function returnSession(isAdmin) {
    if(isAdmin) {
        profile.isAdmin = true;
        return done(null, profile);
    } else {
        return done(null, profile);
    }
};

Then, if I want to protect any API route I'm going:

function isAdmin (req) {
    if (req.isAuthenticated() && req.user.isAdmin) {
        return true;
    } else {
        return false;
    }
}

router.get('/test', function(req, res){
    if(isAdmin(req)) {
        // This user has access
    } else {
        // User is not an admin
    }
});

Here is how I'm passing session to socket.io:

var sessionMW = session({
    store: new RedisStore({ host: 'localhost', port: 6397, client: redis}),
    secret: 'blah-blah', // my secret key to hash sessions
    name: 'nameOfCookie',
    resave: true,
    saveUninitialized: true
});

var app = express();
// ...
app.use(sessionMW);
// ...
app.use(passport.initialize());
app.use(passport.session());
// ...
//Body parser MW
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
// ...
passport.session();
//...
io.use(function(socket, next) {
    // Wrap the express middleware
    sessionMW(socket.request, {}, next);
});

Then, if I want to check if certain socket was emitted by an admin:

function isAuthenticated(socket) {
    if(socket.request.session.hasOwnProperty('passport') && socket.request.session.passport.hasOwnProperty('user')) {
        return true;
    } else {
        return false;
    }
};
function isAdmin(socket) {
    if(socket.request.session.hasOwnProperty('passport') && socket.request.session.passport.hasOwnProperty('user')) {
        if(socket.request.session.passport.user.hasOwnProperty('isAdmin')) {
            return socket.request.session.passport.user.isAdmin;
        } else {
            return false;
        }
    } else {
        return false;
    }
};

And the socket event itself:

socket.on('someProtectedEvent', function(data) {
    if(isAdmin(socket)) {
        // User has rights to use this event
    } else {
        // User is not an admin
    }
});

So, are my dashboard, routes and sensitive socket.io events protected enough? I mean, can anyone bypass these verifications in easy way, or just set this boolean "isAdmin" to true in their own session? Or am I going right way and my dashboard and admin-events are enough protected?

Thanks for your help in advance



via Danny

user authorization with equals() in javascript

i have made a blog in which if a user made a post only them can edit it. But now i want to make an admin that can edit and delete any post he wants

if(foundBlog.author.id.equals(req.user._id ||  foundBlog.author.username === 
"ADMIN")) {
            next();
        } else {
            res.redirect("back");
        }
       } 

But my code doesn't work.



via fanis theologiths

MongoDB won't return token string search results using mongoose or mongo shell

I'm trying to write a reset password function, so I want to find the user by resetPasswordToken. The result returns that the token expired (no result returned), so I verified the token in the db by going into mongo and executing the same query.

The backend code:

User
    .findOne({resetPasswordToken: token}, function(err, user) {
      if (err) {
        console.log("Server error searching for user.", err);
        callback("Server error searching for user.");
      } else {
        console.log(user);
        if(user){
          console.log("User exists!  Create token for user ", user);
          saveNewPass(user, password, callback);
        } else { 
          console.log("The password reset token has expired.  Request a new reset password link.");
          callback(null, {message: null, error: 'The password reset token has expired.'});
        }
      }
  });

It returns the password reset token has expired, which means there is no result coming back.

In mongo shell, I first searched for the record using:

db.users.find({username: "myusername"})

Which returns:

{ 
   "_id" : ObjectId("5908913f6e738b1eef729119"), 
   "username" : "myusername", 
   "password" : "$2a$10$jL5BuxYSA/jiiGiwCxKAGO7ISNaOiFTqX1.RUqJrcVA7x4kgfVD8u", 
   "resetPasswordExpires" : ISODate("2017-05-06T23:33:34.036Z"), 
   "resetPasswordToken" : "65bce3ff4183a9e78eb96f71c2f5ea6449369259" 
}

Then, I copied and pasted the string value of the resetPasswordToken attribute, and ran this query:

db.users.find({resetPasswordToken: "65bce3ff4183a9e78eb96f71c2f5ea6449369259"})

I get NOTHING. What is the deal? I originally thought it was that I was doing date comparison in my search, so I removed it. This is strange.



via user3561890

Nodejs & npm kali 2017

I install Nodejs and NPM in Kali 2017, I can install npm packages but when I tried to use some package, bash: command not found, :s Help? node -v v6.10.3

npm -v 3.10.10

npm config get prefix /root/.npm-global



via Pablo Fernandez

Reading from a CSV File to JSON returns an empty array

So I have this function which prints out json object as strings:

GetAllArticles: (req, res) => {
        var allArticles = getAllArticles();

        res.setHeader("Content-Type", 'application/json');
        res.write(JSON.stringify(allArticles));  //cast object to string

        res.end();
}

Here is my getAllArticles:

function getAllArticles() {
    var result = [];
    result.push(new Article('Gummistiefel', 100, 34.99));
    result.push(new Article('Regenmantel', 10, 124.99));
    result.push(new Article('HTML5 Buch', 25, 4.99));

    //creates a test file
    var json2csv = require('json2csv');
    var fs = require('fs');
    var fields = ["articleName", "quantity","price"];

    var csv2 = json2csv({ data: result, fields: fields });

    fs.writeFile('file.csv', csv2, function (err) {
        if (err) throw err;
        console.log('file saved');
    });

    result = [];//clear the array to save new articles

    //load file
    const csvFilePath = 'file.csv'
    const csv = require('csvtojson')
    csv()
        .fromFile(csvFilePath)
        .on('json', (jsonObj) => { 

            result.push(jsonObj);
        })
        .on('done', (error) => {
             console.log('end');
        })



    return result;
}

Article:

function Article(articleName, quantity, price) {
    this.articleName = articleName;
    this.quantity = quantity;
    this.price = price;
}

And the output on the webpage is: [] So I checked if the loaded jsonObject were in the array and they were, but after I convert them to string the output is just "[]"..



via KeyNavas

svg2png on Heroku - TypeError: Bad argument

I have a problem with svg2png package on Heroku. It works on my machine locally (Windows), but I can't get it working on Heroku free dyno.

The idea is to get svg from Wikipedia and return it as png. I've exposed two endpoints:

  • / - that uses code stored in separated file,
  • /simple - same code, but just in the callback.

When browsing both endpoints I receive Heroku Application error page. That's what I get in Heroku logs for both requests:

TypeError: Bad argument

Do you have an idea?

index.js

const svg2png = require('svg2png')
const axios = require('axios')
const express = require('express')
const bodyParser = require('body-parser')
const conv = require('./conv')

const svgUrl = 'https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg'

const app = express()

app.use(bodyParser.json({limit:'5mb'}))
app.use(bodyParser.urlencoded({extended:true,limit:'5mb'}))

app.get('/simple', function (req, res) {
    axios.get(svgUrl)
        .then(response => {
            return svg2png(response.data, { width: 150, height: 150 })
        })
        .then(pngFile => {
            var img = new Buffer(pngFile, 'base64')
            res.writeHead(200, {
                'Content-Type': 'image/png',
     'Content-Length': img.length
            })
            res.end(img)
        })
})

app.get('/', function (req, res) {
conv.send()    
        .then(pngFile => {
            var img = new Buffer(pngFile, 'base64')
            res.writeHead(200, {
                'Content-Type': 'image/png',
     'Content-Length': img.length
            })
            res.end(img)
        })
})

app.listen(process.env.PORT || 5000, function () {
    console.log('Application started')
})

conv.js

const axios = require('axios')
const svg2png = require('svg2png')

module.exports = {
    send() {
        const self = this;
                self.width = 300;
        self.height = 300;

        const svgUrl = 'https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg'
        return new Promise((resolve, reject) => {
            axios.get(svgUrl)
            .then(response => 

            svg2png(response.data,
             { width: self.width, height: self.height })
            .then(img=>resolve(img))
            .catch(e => {
                console.log('Something went wrong during svg2png conversion.' + e)
                reject(e)
            }))
        });

    }
}



via Robert Skarżycki

mongodb connect fail in osx

I'm newer to mongode, I use shell to start mongodb service but failed and get following error. What should I do?

MongoDB shell version v3.4.4 connecting to: mongodb://127.0.0.1:27017 2017-05-07T07:59:40.141+1000 W NETWORK [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused 2017-05-07T07:59:40.142+1000 E QUERY [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed : connect@src/mongo/shell/mongo.js:237:13 @(connect):1:6 exception: connect failed



via Kevin

Issue with routing in react app

I have a web app. Back end with node and front end with React. Setup goes like this:

index.js
client
package.json

The client

Now, the client folder contains a front end web application, its contents are basically same as what you get when you type create-react-app.

Inside client there is a build folder which I created by running npm run build from within the client folder.

Server

Now, the index.js from my main folder acts as the node server, inside it I have a line like:

app.use(express.static(__dirname + "/client/build"));

Using this approach I have merged my node server and a client front end application (located inside client folder). You can see I told the server to serve files from the client/build.

All was working fine, till I encountered this.

If I click a react button in my client app which has manually calls my router using say:

this.props.router.push('/listmovies');

it correctly shows the page.

But if I type same page in URL address bar I get error:

Cannot GET /listmovies

The latter error I am pretty sure comes from node server. Because there is no listener for listmovies. You see basically I think node is intercepting the call and giving me an error. Whereas in my former case where I called router.push I get a correct page.

I hope I managed to explain my problem. Can someone help how to avoid this situation?



via giorgi moniava

Execute a function after a tree walk has completed with callbacks

I have a simple tree with ids that are keys to a Mongo collection. I'm using a node library called treewalker. As I walk each node of the tree, I'm trying to look up the name (using mongoose) and simply append it to the current node. If I don't do a callback to lookup the node name, and just use some fixed value, I get the value I'm expecting. Let me illustrate in code:

Here is my tree:

{
  "categoryTree": [
    {
      "categoryId": "1",
      "children": [
        {
          "categoryId": "2",
          "children": [
            {
              "categoryId": "3",
              "children": []
            },
            {
              "categoryId": "4",
              "children": []
            }
          ]
        },
        {
          "categoryId": "5",
          "children": []
        },
        {
          "categoryId": "6",
          "children": []
        }
      ]
    },
    {
      "categoryId": "7",
      "children": [
        {
          "categoryId": "8",
          "children": []
        }
      ]
    }
  ]
}

Here is code that does what I want:

catTree.categoryTree.forEach(function(node){
    var counter = 0;
    tree.walkTree(node, 'children', function(obj){
        obj.name = counter++;
    });
});
//This tree has the names (as the counter above) in it as I expect
console.log(JSON.stringify(catTree));

However, as soon as I throw in a mongoose callback to get the category name, the category tree that's printed no longer has the names.

catTree.categoryTree.forEach(function(node){
    tree.walkTree(node, 'children', function(obj){
        //Cat is a mongoose model defined elsewhere
        Cat.findById(obj.categoryId, {_id:0,name:1}).exec(function(err, value){
            obj.name = value.name;
        });
    });
});
//This tree has NO names :(
console.log(JSON.stringify(catTree));

I know this is an issue of timing, but I can't figure out how to solve it. I've seen several SO Articles like this one that suggest tracking callbacks and continuing only after they've all been called. I can't figure out how to apply that pattern to my case because I'm walking a tree and not just iterating a flat list. I'm starting to think that my problem might that I'm using the treewalker library, vs. just writing my own algorithm with callbacks after each node is visited.

I really appreciate your help!



via tobyb

How to integrate Node.js into a PHP Website?

I find PHP way easier to understand and generally use than Node.js, however there's some parts of a website that are "impossible" to make with only PHP, such as realtime chat, realtime notifications, etc.

I was wondering how I could possibly integrate Node.js(& socket.io) in a website (PHP), meaning that the forms, inputs, etc... would be processed and stored using PHP & MySQL, but at the same time use Node.js to process the already stored Username / Message and rendering them realtime.

There's already some answers here on StackOverflow however I couldn't seem to get any of them working.



via Sidexx

Having trouble with my node-Api validating my react client-side jwt-token

I've just started using Auth0 and its really cool, but im running into some issues.

My main issue is that I have a react client-side app that is saving the jwt token on user login - which is great. However when I try to fetch data from my separate Node API - the route that is supposed to validate the token is giving me errors.

If I have my node api using this first type of authentication, I get an error: UnauthorizedError: secret or public key must be provided

const checkJwt = jwt({
  secret: jwksRsa.expressJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: "https://smbtodos.auth0.com/.well-known/jwks.json"
    }),
    audience: 'https://localhost:3001/api/jokes/celebrity',
    issuer: "https://smbtodos.auth0.com/",
    algorithms: ['RS256']
});

BUT, if I use this second form of validation, it seems to work. My concern is that Im not 100% sure its as secure. If there is no token - this validation give me this error when the token is not valid: UnauthorizedError: jwt malformed

const authCheck = jwt({
  secret: 'my-secret',
  // If your Auth0 client was created before Dec 6, 2016,
  // uncomment the line below and remove the line above
  // secret: new Buffer('AUTH0_SECRET', 'base64'),
  audience: 'my-domain'
});

Here is my lock file on react:

import { setSecret } from './auth'

import uuid from 'uuid'

const getLock = (options) => {
  const config = require('../config.json')
  const Auth0Lock = require('auth0-lock').default
  return new Auth0Lock(config.AUTH0_CLIENT_ID, config.AUTH0_CLIENT_DOMAIN, options)
}

const getBaseUrl = () => `${window.location.protocol}//${window.location.host}`

const getOptions = (container) => {

  return {
    allowedConnections: ['Username-Password-Authentication'],
    container,
    closable: false,
    auth: {
      responseType: 'token id_token',
      domain: 'smbtodos.auth0.com',
      redirectUrl: `${getBaseUrl()}/auth/signed-in`,
      params: {
      scope: 'openid profile email'
      }
    }
  }
}

export const show = (container) => getLock(getOptions(container)).show()
export const logout = () => getLock().logout({ returnTo: getBaseUrl() })

And here is my api call in react:

static getJokes(access){
        console.log(access.token)
        return new Promise((resolve, reject) => {

            fetch('http://localhost:3001/api/jokes/celebrity', {
                    method: 'GET',
                    headers: { 
                         Authorization: `Bearer ${access.token}`,
                    } 
                })
                .then( r => {
                    const result = r.json()
                    return result
                } )
                .then( res => {
                    resolve({jokes: res})
                    console.log('api resp 200');
                })
                .catch(e => {
                    reject(e)
                    // console.log(e)
                })

        });

    }
} 

So do I need to make the first option work for better security, if so how? Is the second option of api validation just as good? I feel like I've looked at over 100 tutorials over the last 2 days and they are either out of day, or just are not easy to follow. Im using the most current version of Auth0.

Looking for any help - thank you.



via Spencer Bigum

I cant seem to create a database in Mysql using node.js? How can i create a database in node.js?

I am trying to create a database using mysql using node.js. Whenever I type mysql -v on a terminal on mac I get this.

ERROR 1045 (28000): Access denied for user 'Andrew'@'localhost' (using password: NO)

I have brew, node, npm all installed and updated I think. When I run brew,node,npm - v I get the following.

Andrews-MacBook-Pro:Desktop Andrew$ brew -v
Homebrew 1.2.0
Homebrew/homebrew-core (git revision 1b3b; last commit 2017-05-06)
Andrews-MacBook-Pro:Desktop Andrew$ node -v
v7.10.0
Andrews-MacBook-Pro:Desktop Andrew$ npm -v
4.2.0

I am succesfull in creating a connection using the following script. It displays connected! once executed in terminal.

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: ""
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});

However I cannot create a database using the following script.

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: ""
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  con.query("CREATE DATABASE mydb", function (err, result) {
    if (err) throw err;
    console.log("Database created");
  });
});
Run example »

The following message is displayed if executed in terminal.

/Users/Andrew/Desktop/table.js:17
Run example »
    ^^^^^^^
SyntaxError: Unexpected identifier
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)
    at startup (bootstrap_node.js:151:9)



via INternet Nub

Get "Undefined" for snapshot values

I am currently in the process of setting up my Firebase Cloud functions to have a user to user push notification everytime there is a new child added to "Messages". For each user, there is a notification stored in a node in this structure "/User/UID/Token". However, in my logs in the Firebase console it turns up that values being returned is "Undefined". This is my first time working with Node.js so everything is very new. Any help would be appreciated. Here is what is inside of function

const functions = require('firebase-functions');

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

// Listens for new messages added to messages/:pushId
exports.messageWritten =     functions.database.ref('/messages/{pushId}').onWrite( event => {

console.log('Push notification event triggered');

//  Grab the current value of what was written to the Realtime   Database.
var valueObject = event.data.val();
console.log(valueObject.text,valueObject.toId);

return admin.database().ref(`/Users/${valueObject.toId}`).once('value').then(snapshot =>{
    console.log('the users name',snapshot.name)
    console.log('the users token',snapshot.token)
})


// Create a notification
const payload = {
    notification: {
        title:snapshot.name +' sent you a message', 
        body: valueObject.text,
        sound: "default"
    },
};

 //Create an options object that contains the time to live for the  notification and the priority
const options = {
    priority: "high",
    timeToLive: 60 * 60 * 24
};


  return admin.messaging().sendToDevice(snapshot.token, payload, options);
});



via oneQuestionAsker

How do I start with microservices, docker, kubernetes for an application built with nodejs and reactjs?

The question is purely opinion based. I am looking for a proper way to learn mentioned set of tools/technologies and build production ready application on my local system.

Actually I read one article from Javascript weekly newsletter. It's a pretty interesting article and might be an architecture of future apps. Below is the link:

https://circleci.com/blog/its-the-future/

I am ready to buy some online courses for this as well.



via Valay Desai

Node module that detect updates on webpage

I am looking for a node module that can detect changes/updates of a webpage.

For example, I want to create a watch on https://www.google.com

any updates on that page will trigger an event.

Did some search but can't find one.

Better to have a module that don't depend on any database.



via harrywilson

How to save a csv File using fast-csv that every attribute is in OWN column

So I tried this example:

var csv = require("fast-csv");
    var fs = require("fs");
    var csvStream = csv.createWriteStream({ headers: true }),
        writableStream = fs.createWriteStream("my.csv");

    writableStream.on("finish", function () {
        console.log("DONE!");
    });

    csvStream.pipe(writableStream);
    csvStream.write({ a: "a0", b: "b0" });
    csvStream.write({ a: "a1", b: "b1" });
    csvStream.write({ a: "a2", b: "b2" });
    csvStream.end();

And I get this output:

enter image description here

But I want this output:

enter image description here

Is it possible that the values of a object are in another columns using fast-csv? Or is there another way that it is possible?



via igodie

Importing nodejs `fs` with typescript when executing with ts-node?

I'm trying to run the following code with ts-node.

import { writeFileSync, readFileSync } from 'fs';

However I get:

src/main/ts/create.ts (1,45): Cannot find module 'fs'. (2307)

What do I need to do in to allow typescript to import the fs module?



via Ole

How can I pass parameters when calling a Node.js script from PHP exec()?

I'm trying to implement iOS push notifications. My PHP version stopped working and I haven't been able to get it working again. However, I have a node.js script that works perfectly, using Apple's new Auth Key. I am able to call that from PHP using:

chdir("../apns");
exec("node app.js &", $output);

However, I would like to be able to pass the deviceToken and message to it. Is there any way to pass parameters to the script?

Here's the script I'm trying to run (app.js):

var apn = require('apn');

var apnProvider = new apn.Provider({  
     token: {
        key: 'apns.p8', // Path to the key p8 file
        keyId: '<my key id>', // The Key ID of the p8 file (available at https://developer.apple.com/account/ios/certificate/key)
        teamId: '<my team id>', // The Team ID of your Apple Developer Account (available at https://developer.apple.com/account/#/membership/)
    },
    production: false // Set to true if sending a notification to a production iOS app
});

var deviceToken = '<my device token>';
var notification = new apn.Notification();
notification.topic = '<my app>';
notification.expiry = Math.floor(Date.now() / 1000) + 3600;
notification.badge = 3;
notification.sound = 'ping.aiff';
notification.alert = 'This is a test notification \u270C';
notification.payload = {id: 123};

apnProvider.send(notification, deviceToken).then(function(result) {  
    console.log(result);
    process.exit(0)
});



via Lastmboy

Inheritance in Java (public or private for class fields?)

public class Square {
  public double height;
  public double width;
  public double surfaceArea;

  Square(double height, double width) {
    this.height = height;
    this.width = width;
  }

  public void setHeight(double height) {
    this.height = height;
  }

  public double getHeight() {
    return this.height;
  }

  public void setWidth(double width) {
    this.width = width;
  }

  public double getWidth() {
    return this.width;
  }

  public double computeSurfaceArea() {
    this.surfaceArea = this.height * this.width;
    return this.surfaceArea;
  }

  public double getSurfaceArea() {
    return this.surfaceArea;
  }
}

public class Cube extends Square {
  private int depth = 6;

  Cube(double height, double width) {
    super(height, width);
  }

  public double computeSurfaceArea() {
    super.surfaceArea = (super.height * super.width) * depth;
    return super.surfaceArea;
  }
}

import java.util.Scanner;

public class DemoSquare {
  public static void main(String args[]) {
    Scanner input = new Scanner(System.in);

    Square square;
    Cube cube;

    double doubleValue1, doubleValue2;

    System.out.print("Enter value for height: \n>> ");
    doubleValue1 = input.nextDouble();

    System.out.print("Enter value for width: \n>> ");
    doubleValue2 = input.nextDouble();

    square = new Square(doubleValue1, doubleValue2);
    cube = new Cube(doubleValue1, doubleValue2);

    System.out.println("\n<Results>\n");
    System.out.println("Surface area of <Square Class>: " + square.computeSurfaceArea());
    System.out.println("Surface area of <Cube Class>: " + cube.computeSurfaceArea());
  }
}

Is it okay if I make my class fields(Parent class) to public rather than private? It's because im using the concept of inheritance right here. Or should I use the getters/setters method in the parent class.



via Sean

database connection error on heroku

I am having trouble posting and getting from my heroku database. I can crud locally(TO PostgreSQL), so it isn't my queries; it must be the way that I have configured my database connection. I have received the following error:

error relation "blogs" does not exist error: relation "blogs" does not exist at Connection.parseE (/app/node_modules/pg-promise/node_modules/pg/lib/connection.js:539:11) at Connection.parseMessage (/app/node_modules/pg-promise/node_modules/pg/lib/connection.js:366:17) at TLSSocket. (/app/node_modules/pg-promise/node_modules/pg/lib/connection.js:105:22) at emitOne (events.js:96:13) at TLSSocket.emit (events.js:188:7) at readableAddChunk (_stream_readable.js:177:18) at TLSSocket.Readable.push (_stream_readable.js:135:10) at TLSWrap.onread (net.js:542:20)



via LukeCage

Node.js application gets MongoError connection closed

When I try to connect with node.js application I get:

MongoError: connection 0 to 127.0.0.1:27017 closed

var MongoClient = require('mongodb').MongoClient
 ,format = require('util').format;    
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {     
  if(err) throw err;
  var collection = db.collection('student');     
  collection.insert({id:4,name:shyam}, function(err, docs) {              
    collection.count(function(err, count) {         
      console.log(format("count = %s", count));
    });
    // Locate all the entries using find       
    collection.find().toArray(function(err, results) {
      console.dir(results);
      // Let's close the db
      db.close();
    });
  });
})



via shyamji