Saturday 11 March 2017

Angular 2 project setup with Asp.Net MVC on Visual Studio 2015

I am currently learning Angular 2 and am trying to setup an Angular 2 project with Asp.Net MVC setup on Visual Studio 2015. I referred to couple of articles on Internet and they seems to be too overwhelming complex for a beginner to understand and follow.

I am looking for a simple project setup and I tried to create one but I am getting few errors which I can't seem to solve.

Can anyone help me with resolving the error or redirect me to some articles with simple project setup illustrations?

I have performed the following basic steps,

  1. Created new 'Asp.Net Web Application (.NET Framework)' project with Blank MVC template (no authentication and no unit tests)
  2. Downloaded the 'quickstart-master' angular 2 seed project from Angular 2 official site
  3. Copied the full 'src' folder from seed project to my angular project.
  4. Copied the other remaining files (package.json, bs-config.json, tslint.json, .editorconfig). Basically files which are not mentioned in non-essential-files.txt file
  5. Restored all packages successfully from package.json file
  6. Added a controller 'HomeController'
  7. Added a _Layout.cshtml
  8. Added a _ViewStart.cshtml
  9. Added an Index.html corresponding to Index() action method in HomeController
  10. Copied the JS script references from index.html in seed project to _Layout.html
  11. Copied the body content from index.html to Index.cshtml
  12. Rebuild the solution
  13. Run the solution.

When I try run the solution, I get the below error,

enter image description here

My Project setup looks as below,

enter image description here

Tsconfig.json remains unchanged.

enter image description here

The error,

GET http://localhost:63777/styles.css 
localhost/:14 GET http://localhost:63777/systemjs.config.js 404 (Not Found)
zone.js:2019 GET http://localhost:63777/main.js 404 (Not Found)
scheduleTask @ zone.js:2019
ZoneDelegate.scheduleTask @ zone.js:353
Zone.scheduleTask @ zone.js:196
Zone.scheduleMacroTask @ zone.js:210
(anonymous) @ zone.js:2043
send @ VM96:3
fetchTextFromURL @ system.src.js:1051
(anonymous) @ system.src.js:1778
ZoneAwarePromise @ zone.js:729
(anonymous) @ system.src.js:1777
(anonymous) @ system.src.js:2806
(anonymous) @ system.src.js:3384
(anonymous) @ system.src.js:3707
(anonymous) @ system.src.js:4099
(anonymous) @ system.src.js:4562
(anonymous) @ system.src.js:4831
(anonymous) @ system.src.js:407
ZoneDelegate.invoke @ zone.js:334
Zone.run @ zone.js:126
(anonymous) @ zone.js:713
ZoneDelegate.invokeTask @ zone.js:367
Zone.runTask @ zone.js:166
drainMicroTaskQueue @ zone.js:546
(index):16 ZoneAwareError {__zone_symbol__error: Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:63777/main.js
    Error: XHR error…, __zone_symbol__stack: "(SystemJS) XHR error (404 Not Found) loading http:…t>]↵   Error loading http://localhost:63777/main.js", originalErr: ZoneAwareError, __zone_symbol__currentTask: ZoneTask}__zone_symbol__currentTask: ZoneTask__zone_symbol__error: Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:63777/main.js
    Error: XHR error (404 Not Found) loading http://localhost:63777/main.js
        at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://localhost:63777/node_modules/zone.js/dist/zone.js:1242:29) [<root>]
        at Zone.runTask (http://localhost:63777/node_modules/zone.js/dist/zone.js:166:47) [<root> => <root>]
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:63777/node_modules/zone.js/dist/zone.js:420:38) [<root>]
    Error loading http://localhost:63777/main.js
        at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://localhost:63777/node_modules/zone.js/dist/zone.js:1242:29) [<root>]
        at Zone.runTask (http://localhost:63777/node_modules/zone.js/dist/zone.js:166:47) [<root> => <root>]
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:63777/node_modules/zone.js/dist/zone.js:420:38) [<root>]
    Error loading http://localhost:63777/main.js
    at addToError (http://localhost:63777/node_modules/systemjs/dist/system.src.js:122:78) [<root>]
    at linkSetFailed (http://localhost:63777/node_modules/systemjs/dist/system.src.js:687:15) [<root>]
    at http://localhost:63777/node_modules/systemjs/dist/system.src.js:495:9 [<root>]
    at Zone.run (http://localhost:63777/node_modules/zone.js/dist/zone.js:126:43) [<root> => <root>]
    at http://localhost:63777/node_modules/zone.js/dist/zone.js:713:57 [<root>]
    at Zone.runTask (http://localhost:63777/node_modules/zone.js/dist/zone.js:166:47) [<root> => <root>]
    at drainMicroTaskQueue (http://localhost:63777/node_modules/zone.js/dist/zone.js:546:35) [<root>]
    at XMLHttpRequest.ZoneTask.invoke (http://localhost:63777/node_modules/zone.js/dist/zone.js:424:25) [<root>]__zone_symbol__stack: "(SystemJS) XHR error (404 Not Found) loading http://localhost:63777/main.js↵ Error: XHR error (404 Not Found) loading http://localhost:63777/main.js↵        at XMLHttpRequest.wrapFn [as __zone_symbol___onreadystatechange] (http://localhost:63777/node_modules/zone.js/dist/zone.js:1242:29) [<root>]↵       at Zone.runTask (http://localhost:63777/node_modules/zone.js/dist/zone.js:166:47) [<root> => <root>]↵       at XMLHttpRequest.ZoneTask.invoke (http://localhost:63777/node_modules/zone.js/dist/zone.js:420:38) [<root>]↵   Error loading http://localhost:63777/main.js"message: (...)name: (...)originalErr: ZoneAwareErrororiginalStack: (...)stack: (...)toSource: ()toString: ()zoneAwareStack: (...)get message: ()set message: (value)get name: ()set name: (value)get originalStack: ()set originalStack: (value)get stack: ()set stack: (value)get zoneAwareStack: ()set zoneAwareStack: (value)__proto__: Object
(anonymous) @ (index):16
ZoneDelegate.invoke @ zone.js:334
Zone.run @ zone.js:126
(anonymous) @ zone.js:713
ZoneDelegate.invokeTask @ zone.js:367
Zone.runTask @ zone.js:166
drainMicroTaskQueue @ zone.js:546
ZoneTask.invoke @ zone.js:424



via SamirG

request npm module - resolve ESOCKETTIMEDOUT

I am using request npm module and making upstream requests in a loop approx 100 requests per second. The timeout has been set to 10 seconds. Problem is I keep getting ESOCKETTIMEDOUT for 1 out of 1000 requests consistently.

I am pretty sure that upstream server is not timing out. What could be the reason of this and how to avoid it.



via user27111987

Cannot start monog db

I have did the mongodb installation process mentioned the following link https://docs.mongodb.com/manual/installation/ but i can't start the mongodb this my log kindly tell me the possible way to start mongo db

C:\>"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe"
2017-03-12T12:42:55.378+0530 I CONTROL  [initandlisten] MongoDB starting : pid=5
400 port=27017 dbpath=C:\data\db\ 64-bit host=vimals
2017-03-12T12:42:55.379+0530 I CONTROL  [initandlisten] targetMinOS: Windows 7/W
indows Server 2008 R2
2017-03-12T12:42:55.380+0530 I CONTROL  [initandlisten] db version v3.4.2
2017-03-12T12:42:55.381+0530 I CONTROL  [initandlisten] git version: 3f76e40c105
fc223b3e5aac3e20dcd026b83b38b
2017-03-12T12:42:55.382+0530 I CONTROL  [initandlisten] OpenSSL version: OpenSSL
 1.0.1u-fips  22 Sep 2016
2017-03-12T12:42:55.382+0530 I CONTROL  [initandlisten] allocator: tcmalloc
2017-03-12T12:42:55.383+0530 I CONTROL  [initandlisten] modules: enterprise
2017-03-12T12:42:55.384+0530 I CONTROL  [initandlisten] build environment:
2017-03-12T12:42:55.385+0530 I CONTROL  [initandlisten]     distmod: windows-64
2017-03-12T12:42:55.385+0530 I CONTROL  [initandlisten]     distarch: x86_64
2017-03-12T12:42:55.386+0530 I CONTROL  [initandlisten]     target_arch: x86_64
2017-03-12T12:42:55.387+0530 I CONTROL  [initandlisten] options: {}
2017-03-12T12:42:55.389+0530 I STORAGE  [initandlisten] exception in initAndList
en: 98 Unable to create/open lock file: C:\data\db\mongod.lock The process canno
t access the file because it is being used by another process.. Is a mongod inst
ance already running?, terminating
2017-03-12T12:42:55.390+0530 I NETWORK  [initandlisten] shutdown: going to close
 listening sockets...
2017-03-12T12:42:55.390+0530 I NETWORK  [initandlisten] shutdown: going to flush
 diaglog...
2017-03-12T12:42:55.391+0530 I CONTROL  [initandlisten] now exiting
2017-03-12T12:42:55.392+0530 I CONTROL  [initandlisten] shutting down with code:
100



via vimal kumar

heroku local web ssl using self signed certificate

I'm using the heroku toolbelt to start a development version of my web server locally, e.g. heroku local web. This has always worked well enough, but I recently added https encryption to all pages of my site via the heroku addon expeditedSSL and express-sslify and localhost now shows this message in chrome

This site can’t be reached

localhost unexpectedly closed the connection.

I would like to add a local, self-signed ssl certificate for use when operating in a https localhost environment. I've read a few posts about creating self signed certificates that are supposed to work with node.js servers, but no matter what I try I always see the persistent chrome message.

I suspect my problems are somewhat sourced from what heroku local web actually does in starting up the web server. How do I get a local instance of a heroku server to use self signed ssl certificate?



via GrantD71

Send json data (asynchronous) to my response

So,upon request I respond with a basic template(I use ejs) and I want to add json data to it when I get from an external API. I have noticed that I can't use res.render or res.write twice(I get errors) so I really don't know what to do.Any ideas?



via stop

How to setup Braintree API in node js?

I want use braintree for website paymentgateway, unfortunately when I follow the guideline online, & the code unable to be use in node js. Is anything missing?

Index.js:

//send token to clients

app.get("/client_token", function (req, res) {
  gateway.clientToken.generate({}, function (err, response) {
    res.send(response.clientToken);
  });
});

//Receive payment from clients

app.post("/checkout", function (req, res) {
  var nonceFromTheClient = req.body.payment_method_nonce;
  // Use payment method nonce here
});

//Test sandbox
gateway.transaction.sale({
  amount: "10.00",
  paymentMethodNonce: nonceFromTheClient,
  options: {
    submitForSettlement: true
  }
}, function (err, result) {

  if (err) {
    console.error(err);
    return;
  }

  if (result.success) {
    console.log('Transaction ID: ' + result.transaction.id);
  } else {
    console.error(result.message);
  }
});

Error unable pass the node js npm start:

paymentMethodNonce: nonceFromTheClient,

Details in IDE:

ReferenceError: nonceFromTheClient is not defined

at Object.<anonymous> (/Users/desmondkam/codecampvn/index.js:37:23)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:456:32)
at tryModuleLoad (module.js:415:12)
at Function.Module._load (module.js:407:3)
at Function.Module.runMain (module.js:575:10)
at startup (node.js:160:18)
at node.js:445:3



via Kimson101

Sequelize and Node.js: Initializing Multiple Databases On One Server Programmatically

When I run the server attempting to create two databases (db1 and db2), the system kicks backs this error:

Possibly unhandled SequelizeBaseError: database "db2" does not exist

As a reference, there is similar stackoverflow question on this topic here, however, the author of the solution does not cover the solution to how the server.js file is setup. You will notice I have structured my index.js file similar to their answer.

My models/index.js file and server run and executes scripts properly, yet the second database does not work at all and does not even get initialized.

Can someone provide a solution for the server.js file to accurately initialize two databases in this one server?

The following is the partial code from the models/index.js and server.js files. In the server.js file, I am using .sync to initialize the databases.

models/index.js

    var databasesArray = ['db1', 'db2']
    var databasesObj = {
        database: {
            db1: {
                DBName: 'db1',
                User: user,
                Password: password,
                Config: config,
            },
            db2: {
                DBName: 'db2',
                User: user,
                Password: password,
                Config: config,
            }
        }
    } // EOF databaseObj                                                                                                                                                                     

    for(var i = 0; i < databasesArray.length; ++i) {
        var databasePointerToOBJ = databasesArray[i];
        var database = databasesObj.database[databasePointerToOBJ]
        if(database.DBName == 'db1'){
            var sq = new Sequelize(database.DBName, user, password, config)
            db['db1'] = {
                Sequelize: Sequelize,
                sequelize: sq,
                Table1: sq.import(__dirname + '/...')
            }
        }else if(database.DBName == 'db2'){
            var sq = new Sequelize(database.DBName, user, password, config)
            db['db2'] = {
                Sequelize: Sequelize,
                sequelize: sq,
                Table1: sq.import(__dirname + '/...')
            }
        }
    }
module.exports = db;

server.js

    [...] 
    //sync's sequelize DB tables                                                                                                                                                                     
    db['db1'].sequelize.sync(function(err){});
    db['db2'].sequelize.sync(function(err){});



via JMM

How can I launch node to run a .ts file from intellij?

I have a project set up with intellij IDEA happily compiling .ts typescript files to .js ES6 files. The .js files are being dumped neatly next to the .ts files.

directory tree

I'd like to the able to run the .ts files in node.js just like I can with the .js files. Eg using CMD+SHIFT+F10 on .ts intellij will launch node .js (after running the typescript compiler). After each file edit it feels awkward having to remember to open the .js version before running the file I just edited.

The equivalent experience for a java programmer would be navigating to the .class version of a unit test to execute the edited .java file.

Is this just a missing feature in intellij/webstorm or am I missing something?



via aussie1984

Compiling TypeScript to JavaScript using Visual Studio Code

I am new to NodeJS and TypeScript and I want to begin by setting up my project folder. I already have my tsconfig.json

{
"compilerOptions": {
    "outDir": "./build",
    "module": "commonjs",
    "target": "es5",
    "noImplicitAny" : false
},
"files": [
    "./src/**/*.ts"
],
"exclude": [
    "node_modules"
]}

and package.json

    {
      "name": "crm",
      "version": "1.0.0",
      "description": "",
      "main": "app.js",
      "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC"
    }

This is my simple directory structure:

    crm/
     |-src/
       |- main/
          |- app.ts

when I compile it using the tsc command, I expected that the compiled directory will be

    crm/
     |- src/
        |- main/
           |- app.js

but the result is

    crm
     |- build/
        |- app.js

there is no main folder that is created.

I dont know if the problem is on tsconfig.json or in the tsc command



via Gerald

PassportJS not passing signup data to database

I'm using a scotch.io tutorial on setting up PassportJS local login for an app I'm working on. After setting up my signup/login pages, MongoDB, PassportJS, I tried making a test "account", and.... nothing happens. No redirect, no flash message, nothing. It seems like nothing is getting picked up to post to the database. I'm including the pertinent scripts below. I tried to be as faithful as possible to the tutorial layout (source: https://scotch.io/tutorials/easy-node-authentication-setup-and-local).

index.js (entry point for server)

// load dependencies
var express = require('express');
var app = express();
var path = require('path');

var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var LocalStrategy = require('passport-local').Strategy;

var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var session = require('express-session');

var configDB = require('./config/database.js');

// setup views
var ejs = require('ejs');
var engine = require('ejs-locals');

//database configuration
mongoose.connect(configDB.url);

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

app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

//view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/public', express.static(path.join(__dirname, 'public')));

// required for passport
app.use(session({ 
    secret: 'ilovescotchscotchyscotchscotch',
    resave: true,
    saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // for flash messages stored in-session

// routes
require('./routes')(app, passport);

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
});

passport.js (passport settings)

var LocalStrategy = require('passport-local').Strategy;

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

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

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

    passport.use('local-signup', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true
    },
    function(req, email, password, done) {
        process.nextTick(function() {
            User.findOne({ 'local.email': email }, function(err, user) {
                if (err)
                    return done(err);
                if (user) {
                    return done(null, false, req.flash('signupMessage', 'That e-mail address is already taken.'));
                } else {
                    var newUser = new User;
                    newUser.local.email = email;
                    newUser.local.password = newUser.generateHash(password);
                    newUser.save(function(err) {
                        if (err)
                            throw err;
                        return done(null, newUser);
                    });
                }
            });
        });
    }));

    passport.use('local-login', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true
    },
    function(req, email, password, done) {
        User.findOne({ 'local.email': email }, function(err, user) {
            if (err)
                return done(err);
            if (!user)
                return done(null, false, req.flash('loginMessage', 'User not found.'));
            if(!user.validPassword(password))
                return done(null, false, req.flash('loginMessage', 'Invalid password, please try again.'));
            return done(null, user);
        });
    }));
};

/config/database.js

module.exports = {
    'url': 'mongodb://localhost:27017/users/'
}

routes.js

module.exports = function(app, passport) {
    app.get('/', function (req, res) {
        res.render('pages/index');
    });

    app.get('/login', function (req, res) {
        res.render('pages/login', { message: req.flash('loginMessage') });
    });

    app.get('/signup', function (req, res) {
        res.render('pages/signup', { message: req.flash('signupMessage') });
    });

    app.post('/signup', passport.authenticate('local-signup', {
        successRedirect: '/profile',
        failureRedirect: '/signup',
        failureFlash: true
    }));

    app.post('/login', passport.authenticate('local-login', {
        successRedirect: '/profile',
        failureRedirect: '/login',
        failureFlash: true
    }));

    app.get('/profile', isLoggedIn, function(req, res) {
        res.render('profile.ejs', {
            user: req.user
        });
    });

    app.get('/addroom', function (req, res) {
        res.render('pages/addroom.ejs', {
            message: req.flash('addroomMessage')
        });
    });

    app.get('/propconfig', function (req, res) {
        res.render('pages/propconfig.ejs', {
            message: req.flash('propconfigMessage')
        });
    });
    app.get('/logout', function(req, res) {
        req.logout();
        res.redirect('/');
    });
};

// route middleware to ensure a user is logged in
function isLoggedIn(req, res, next) {
    if (req.isAuthenticated())
        return next();
    res.redirect('/');
}

user.js (user schema)

// load dependencies
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');

// define user schema
var userSchema = mongoose.Schema({
    local: {
        email: String,
        password: String
    }
});

// METHODS
// generating a hash

userSchema.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

// checking if password is valid
userSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.local.password);
};

// creating model for user to expose to app
module.exports = mongoose.model('User', userSchema);

and finally, signup.ejs (template for signup UI)

<!doctype html>
<html>
<head>
    <title>Node Authentication</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
    <style>
        body        { padding-top:80px; }
    </style>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
    <script   src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js"   integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="   crossorigin="anonymous"></script>
</head>
<body>
<div class="container">

<div class="col-sm-6 col-sm-offset-3">

    <h1><span class="fa fa-sign-in"></span> Signup</h1>

    <!-- show any messages that come back with authentication -->
    <% if (message.length > 0) { %>
        <div class="alert alert-danger"><%= message %></div>
    <% } %>

    <!-- LOGIN FORM -->
    <form action="/signup" method="post">
        <div class="form-group">
            <label>Email</label>
            <input type="text" class="form-control" name="email" id="email">
            <div id="emailError"></div>
        </div>
        <div class="form-group">
            <label>Password</label>
            <input type="password" class="form-control" name="password" id="password">
            <div id="passwordError"></div>
        </div>

        <button type="submit" class="btn btn-warning btn-lg">Signup</button>
    </form>

    <hr>

    <p>Already have an account? <a href="/login">Login</a></p>
    <p>Or go <a href="/">home</a>.</p>

</div>

</div>
<script type="text/javascript" src="../public/javascripts/validate.js"></script>
</body>
</html>



via Matt

Using a function that includes a promise the set the value of a variable?

Iv been scratching my head over this for quite a while now, and a massive search over the internet has proved unsuccessful. Hopefully somebody here can help.

Im trying to set the value of a variable by calling a function, but the function contains a Promise. and is only returning and empty string value.

Here is my code (I will walk through it):

//make connection to mysql DB
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '*********',
database: 'prioritySpeaker'
});
var table = 'speaker';
connection.connect(function(err, results) {
    if (err) {
        console.log("ERROR: " + err.message);
        throw err;
    };
    console.log("connected.");
});
    var priorityRole = role();
    function role(){
        var role = "";
        connection.query(`SELECT priorityRole from ${table} WHERE uniqueID = "${guildID}"`,function(error,result,field){
        if(result){
            var row = result[0];
            var pRole = row.priorityRole;
            role = pRole;
        }else{
            console.log(error);
        }
    });
    return role;
};
console.log(priorityRole);

So what is happening is: I've created a variable called priorityRole which needs to be the resulting value from the resultof the connection.query.

The function role() creates a variable of role and then runs the connection.query to the mysql server which if it returns with a result should set the value of role to the result as defined in the if statement and then return role as the result. So at the very end I need the priorityRole variable to be the same as the role variable.

Hopefully that all makes sense. I should mention that I am using NodeJS, and I really hope that somebody will be able to help me out with this :)



via Ashton

NodeJS: How do I enable CHACHA20_POLY1305 in https?

I use NodeJS version 7.7.2. Here is my cipher definition:

ciphers: [
        "ECDHE-ECDSA-CHACHA20-POLY1305",
        "ECDHE-ECDSA-AES256-GCM-SHA384",
        "ECDHE-ECDSA-AES256-SHA",
        "!RC4",
        "!AES128"
    ].join(':')

My openssl version is 1.1.0e 16 Feb 2017

Here is what return from openssl ciphers -v 'ECDHE-ECDSA-CHACHA20-POLY1305' command:

ECDHE-ECDSA-CHACHA20-POLY1305 TLSv1.2 Kx=ECDH     Au=ECDSA Enc=CHACHA20/POLY1305(256) Mac=AEAD

However, what return from www.ssllabs.com shows that my website only support AES256 cipher suits:

TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 (0xc02c)   ECDH secp384r1 (eq. 7680 bits RSA)   FS  256
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA (0xc00a)   ECDH secp384r1 (eq. 7680 bits RSA)   FS 256

Did I do something wrong?



via Branya The Great

How do I use nodejs Mysql to get my data into the function after callback

So I'm trying to use nodejs mysql to access my locally running database that I am using for development. Everything is running correctly and I am able to make successful queries to the server and get the data back.

I have the function I created below which I am module.exports so that it is accessible from within my server where it is invoked and the loadExp() method is called.

var dataStore = function (connection) {

    this.con = connection;
    this.clientArr = new Map();

    /**
     * Loads all of the user experiences into the array.
     */
    this.loadExp = function () {

        var output = 'err';

        loadData(this.con, function (err, result) {
            console.log(err || result);
            output = result.uuid;
        });

        console.log(output);
    };

    function loadData(con, callback) {
        con.query('SELECT * FROM exp', function (err, rows, fields) {
            if (err) throw err;
            callback(null, rows);
        });
    }

    /**
     * Returns the value of a client from within the hash map.
     * @param id
     * @returns {*|String}
     */
    this.getClient = function (id) {
        var value = this.clients.get(id);
        if (value != null) {
            return value;
        } else {
            return 'err';
        }
    };

    /**
     * Returns a full list of clients.
     * @returns {Map}
     */
    this.getClientList = function () {
        return this.clientArr;
    };

    /**
     * Creates a new instance of a client within the database and also within our datastore.
     * @param id
     * @param client
     */
    this.addClient = function (id, client) {
        this.clientArr.set(id, client);
    };

};

module.exports = dataStore;

Now I would like to make use of my this.addClient function outlined at the bottom of this function but I can never get my data in scope to make this possible and I'm stuck for how I would get this data in scope so that it is usable.



via li x

Http Request can't send a response immediately in Nodejs server

I send JSON requests one by one to the nodejs server. After 6th request, server can't reply to the client immediately and then it takes a little while(15 seconds or little bit more and send back to me answer 200 ok) It occurs a writing json value into MongoDB and time is important option for me in terms with REST call. How can I find the error in this case? (which tool or script code can help me?) My server side code is like that

var controlPathDatabaseSave = "/save";
app.use('/', function(req, res) {
console.log("req body app use", req.body);
var str= req.path;

if(str.localeCompare(controlPathDatabaseSave) == 0)
{
    console.log("controlPathDatabaseSave");
    mongoDbHandleSave(req.body);
    res.setHeader('Content-Type', 'application/json');
    res.write('Message taken: \n');
    res.write('Everything all right with database saving');
    res.send("OK");
    console.log("response body", res.body);
}

});

My client side code as below:

function saveDatabaseData()
{
    console.log("saveDatabaseData");
        var oReq = new XMLHttpRequest();
        oReq.open("POST", "http://192.168.80.143:2800/save", true);
        oReq.setRequestHeader("Content-type", "application/json;charset=UTF-8");
        oReq.onreadystatechange = function() {//Call a function when the state changes.
            if(oReq.readyState == 4 && oReq.status == 200) {
                console.log("http responseText", oReq.responseText);
            }
        }
        oReq.send(JSON.stringify({links: links, nodes: nodes}));
}

You can see my REST call in google chrome developer editor. (First six call has 200 ok. Last one is in pending state)

enter image description here

Thanks in advance,



via zoint

How can I include multiple files my initial page load using Node

Coming from PHP, I just do ( I'm doing a port from LAMP to MEAN )

<?php inlcude "file.hm">

Is there a simple way to do this in Node?



via zen

Angular2 app works on initial load, but hot-reloading throws `The selector "app" did not match any elements`

On initial page load, the site runs fine and loads the proper data, but when I try to change some of the content, and check to see if hot-reloading is working, it throws these errors.

Error: The selector "app" did not match any elements
    at DomRenderer.selectRootElement (eval at <anonymous> (http://localhost:8080/js/vendor.js:1129:1), <anonymous>:196:23) [angular]
    at DebugDomRenderer.selectRootElement (eval at <anonymous> (http://localhost:8080/js/vendor.js:2480:1), <anonymous>:47:56) [angular]
    at selectOrCreateRenderHostElement (eval at <anonymous> (http://localhost:8080/js/vendor.js:748:1), <anonymous>:509:32) [angular]
    at CompiledTemplate.proxyViewClass.View_AppComponent_Host0.createInternal (/AppModule/AppComponent/host.ngfactory.js:13:16) [angular]
    at CompiledTemplate.proxyViewClass.AppView.createHostView (eval at <anonymous> (http://localhost:8080/js/vendor.js:2529:1), <anonymous>:121:21) [angular]

Since it's loading on the initial load, I'll just post my package.json and webpack.config.js. If more files are needed, I'll post them ASAP.

Any help or guidance is greatly appreciated.


Here's my package.json. I'm running npm run watch in one console and npm run start:hmr in another console.

{
  "name": "site-pinger",
  "version": "1.0.0",
  "description": "",
  "author": "",
  "license": "ISC",
  "scripts": {
    "clean": "rimraf node_modules doc dist && npm cache clean",
    "clean-install": "npm run clean && npm install",
    "clean-start": "npm run clean-install && npm start",
    "watch": "webpack --watch --progress --profile",
    "build": "rimraf dist && webpack --progress --profile --bail",
    "server": "webpack-dev-server --inline --progress --port 8080",
    "webdriver-update": "webdriver-manager update",
    "webdriver-start": "webdriver-manager start",
    "lint": "tslint --force \"src/**/*.ts\"",
    "e2e": "protractor",
    "e2e-live": "protractor --elementExplorer",
    "pretest": "npm run lint",
    "test": "karma start",
    "posttest": "remap-istanbul -i coverage/json/coverage-final.json -o coverage/html -t html",
    "test-watch": "karma start --no-single-run --auto-watch",
    "ci": "npm run e2e && npm run test",
    "docs": "typedoc --options typedoc.json src/app/app.component.ts",
    "start": "npm run server",
    "start:hmr": "npm run server -- --hot",
    "postinstall": "npm run webdriver-update"
  },
  "devDependencies": {
    "@angularclass/hmr": "^1.0.1",
    "@angularclass/hmr-loader": "^3.0.2",
    "@types/jasmine": "2.5.41",
    "@types/node": "^6.0.38",
    "@types/selenium-webdriver": "2.53.39",
    "@types/lodash": "4.14.50",
    "angular2-template-loader": "^0.6.0",
    "autoprefixer": "^6.3.2",
    "awesome-typescript-loader": "^3.0.0-beta.17",
    "codelyzer": "2.0.0",
    "copy-webpack-plugin": "^4.0.0",
    "css-loader": "^0.26.1",
    "extract-text-webpack-plugin": "^2.0.0-beta.4",
    "file-loader": "^0.10.0",
    "html-loader": "^0.4.0",
    "html-webpack-plugin": "^2.8.1",
    "istanbul-instrumenter-loader": "^0.2.0",
    "jasmine-core": "^2.3.4",
    "jasmine-spec-reporter": "^3.2.0",
    "json-loader": "^0.5.3",
    "karma": "1.4.1",
    "karma-chrome-launcher": "^2.0.0",
    "karma-coverage": "^1.0.0",
    "karma-jasmine": "^1.0.2",
    "karma-mocha-reporter": "^2.0.3",
    "karma-remap-istanbul": "0.2.1",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "2.0.2",
    "node-sass": "^4.5.0",
    "null-loader": "0.1.1",
    "postcss-loader": "^1.1.0",
    "protractor": "^4.0.10",
    "raw-loader": "0.5.1",
    "remap-istanbul": "^0.6.4",
    "rimraf": "^2.5.1",
    "sass-loader": "^6.0.1",
    "shelljs": "^0.7.0",
    "style-loader": "^0.13.0",
    "ts-helpers": "^1.1.1",
    "tslint": "^4.3.1",
    "tslint-loader": "^3.3.0",
    "typedoc": "^0.5.1",
    "typescript": "2.0.10",
    "url-loader": "^0.5.6",
    "webpack": "2.2.1",
    "webpack-dev-server": "2.3.0"
  },
  "dependencies": {
    "@angular/common": "~2.4.0",
    "@angular/compiler": "~2.4.0",
    "@angular/core": "~2.4.0",
    "@angular/forms": "~2.4.0",
    "@angular/http": "~2.4.0",
    "@angular/platform-browser": "~2.4.0",
    "@angular/platform-browser-dynamic": "~2.4.0",
    "@angular/router": "~3.4.0",
    "angular-in-memory-web-api": "~0.2.4",
    "systemjs": "0.19.40",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.1",
    "zone.js": "^0.7.4"
  },
  "repository": {}
}


Here's my webpack.config.js

// Helper: root() is defined at the bottom
var path = require('path');
var webpack = require('webpack');

// Webpack Plugins
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');

/**
 * Env
 * Get npm lifecycle event to identify the environment
 */
var ENV = process.env.npm_lifecycle_event;
var isTestWatch = ENV === 'test-watch';
var isTest = ENV === 'test' || isTestWatch;
var isProd = ENV === 'build:watch';

module.exports = function makeWebpackConfig() {
  /**
   * Config
   * Reference: http://webpack.github.io/docs/configuration.html
   * This is the object where all configuration gets set
   */
  var config = {};

  /**
   * Devtool
   * Reference: http://webpack.github.io/docs/configuration.html#devtool
   * Type of sourcemap to use per build type
   */
  if (isProd) {
    config.devtool = 'source-map';
  }
  else if (isTest) {
    config.devtool = 'inline-source-map';
  }
  else {
    config.devtool = 'eval-source-map';
  }

  if (!isTest) {
    /**
     * Entry
     * Reference: http://webpack.github.io/docs/configuration.html#entry
     */
    config.entry = isTest ? {} : {
      'polyfills': './src/polyfills.ts',
      'vendor': './src/vendor.ts',
      'app': './src/main.ts' // our angular app
    };
  }

  /**
   * Output
   * Reference: http://webpack.github.io/docs/configuration.html#output
   */
  config.output = isTest ? {} : {
    path: root('dist'),
    publicPath: isProd ? '/' : 'http://localhost:8080/',
    filename: isProd ? 'js/[name].[hash].js' : 'js/[name].js',
    chunkFilename: isProd ? '[id].[hash].chunk.js' : '[id].chunk.js'
  };

  /**
   * Resolve
   * Reference: http://webpack.github.io/docs/configuration.html#resolve
   */
  config.resolve = {
    // only discover files that have those extensions
    extensions: ['.ts', '.js', '.json', '.css', '.scss', '.html'],
  };

  var atlOptions = '';
  if (isTest && !isTestWatch) {
    // awesome-typescript-loader needs to output inlineSourceMap for code coverage to work with source maps.
    atlOptions = 'inlineSourceMap=true&sourceMap=false';
  }

  /**
   * Loaders
   * Reference: http://webpack.github.io/docs/configuration.html#module-loaders
   * List: http://webpack.github.io/docs/list-of-loaders.html
   * This handles most of the magic responsible for converting modules
   */
  config.module = {
    rules: [
      // Support for .ts files.
      {
        test: /\.ts$/,
        loaders: ['awesome-typescript-loader?' + atlOptions, 'angular2-template-loader', '@angularclass/hmr-loader'],
        exclude: [isTest ? /\.(e2e)\.ts$/ : /\.(spec|e2e)\.ts$/, /node_modules\/(?!(ng2-.+))/]
      },

      // copy those assets to output
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader?name=fonts/[name].[hash].[ext]?'
      },

      // Support for *.json files.
      {test: /\.json$/, loader: 'json-loader'},

      // Support for CSS as raw text
      // use 'null' loader in test mode (https://github.com/webpack/null-loader)
      // all css in src/style will be bundled in an external css file
      {
        test: /\.css$/,
        exclude: root('src', 'app'),
        loader: isTest ? 'null-loader' : ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', 'postcss-loader']})
      },
      // all css required in src/app files will be merged in js files
      {test: /\.css$/, include: root('src', 'app'), loader: 'raw-loader!postcss-loader'},

      // support for .scss files
      // use 'null' loader in test mode (https://github.com/webpack/null-loader)
      // all css in src/style will be bundled in an external css file
      {
        test: /\.(scss|sass)$/,
        exclude: root('src', 'app'),
        loader: isTest ? 'null-loader' : ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', 'postcss-loader', 'sass-loader']})
      },
      // all css required in src/app files will be merged in js files
      {test: /\.(scss|sass)$/, exclude: root('src', 'style'), loader: 'raw-loader!postcss-loader!sass-loader'},

      // support for .html as raw text
      // todo: change the loader to something that adds a hash to images
      {test: /\.html$/, loader: 'raw-loader',  exclude: root('src', 'index.html')}
    ]
  };

  if (isTest && !isTestWatch) {
    // instrument only testing sources with Istanbul, covers ts files
    config.module.rules.push({
      test: /\.ts$/,
      enforce: 'post',
      include: path.resolve('src'),
      loader: 'istanbul-instrumenter-loader',
      exclude: [/\.spec\.ts$/, /\.e2e\.ts$/, /node_modules/]
    });
  }

  if (!isTest || !isTestWatch) {
    // tslint support
    config.module.rules.push({
      test: /\.ts$/,
      enforce: 'pre',
      loader: 'tslint-loader'
    });
  }

  /**
   * Plugins
   * Reference: http://webpack.github.io/docs/configuration.html#plugins
   * List: http://webpack.github.io/docs/list-of-plugins.html
   */
  config.plugins = [
    // Define env variables to help with builds
    // Reference: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
    new webpack.DefinePlugin({
      // Environment helpers
      'process.env': {
        ENV: JSON.stringify(ENV)
      }
    }),

    // Workaround needed for angular 2 angular/angular#11580
      new webpack.ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
        root('./src') // location of your src
      ),

    // Tslint configuration for webpack 2
    new webpack.LoaderOptionsPlugin({
      options: {
        /**
         * Apply the tslint loader as pre/postLoader
         * Reference: https://github.com/wbuchwalter/tslint-loader
         */
        tslint: {
          emitErrors: false,
          failOnHint: false
        },
        /**
         * Sass
         * Reference: https://github.com/jtangelder/sass-loader
         * Transforms .scss files to .css
         */
        sassLoader: {
          //includePaths: [path.resolve(__dirname, "node_modules/foundation-sites/scss")]
        },
        /**
         * PostCSS
         * Reference: https://github.com/postcss/autoprefixer-core
         * Add vendor prefixes to your css
         */
        postcss: [
          autoprefixer({
            browsers: ['last 2 version']
          })
        ]
      }
    })
  ];

  if (!isTest && !isTestWatch) {
    config.plugins.push(
      // Generate common chunks if necessary
      // Reference: https://webpack.github.io/docs/code-splitting.html
      // Reference: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
      new CommonsChunkPlugin({
        name: ['vendor', 'polyfills']
      }),

      // Inject script and link tags into html files
      // Reference: https://github.com/ampedandwired/html-webpack-plugin
      new HtmlWebpackPlugin({
        template: './index.html',
        chunksSortMode: 'dependency'
      }),

      // Extract css files
      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Disabled when in test mode or not in build mode
      new ExtractTextPlugin({filename: 'css/[name].[hash].css', disable: !isProd})
    );
  }

  // Add build specific plugins
  if (isProd) {
    config.plugins.push(
      // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
      // Only emit files when there are no errors
      new webpack.NoEmitOnErrorsPlugin(),

      // // Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
      // // Dedupe modules in the output
      // new webpack.optimize.DedupePlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
      // Minify all javascript, switch loaders to minimizing mode
      new webpack.optimize.UglifyJsPlugin({sourceMap: true, mangle: { keep_fnames: true }}),

      // Copy assets from the public folder
      // Reference: https://github.com/kevlened/copy-webpack-plugin
      new CopyWebpackPlugin([{
        from: root('src/public')
      }])
    );
  }

  /**
   * Dev server configuration
   * Reference: http://webpack.github.io/docs/configuration.html#devserver
   * Reference: http://webpack.github.io/docs/webpack-dev-server.html
   */
  config.devServer = {
    contentBase: './src/public',
    historyApiFallback: true,
    quiet: true,
    stats: 'minimal' // none (or false), errors-only, minimal, normal (or true) and verbose
  };

  return config;
}();

// Helper functions
function root(args) {
  args = Array.prototype.slice.call(arguments, 0);
  return path.join.apply(path, [__dirname].concat(args));
}



via qbolt

What might be preventing an EC2-hosted bot replying to messages on the Microsoft Bot Framework?

I have a Node.JS bot hosted on AWS EC2, with a valid Comodo SSL certificate that works in Chrome/Firefox/Safari and I've configured a bot on the bot framework for my endpoint.

When I launch the bot framework console at https://dev.botframework.com I can click the "test" button and it says "Accepted". I can also send a message in the embedded web chat, and the logging on my bot on AWS shows the message being received, and a message being sent back with a call to session.send()... but the return message never appears back in the web chat. There are no errors logged on the server side or in the bot framework error viewer, the message just seems to be silently dropped. I added a Skype channel and get exactly the same behaviour in Skype.

When I deploy the same code to an Azure Web App it all works fine in both directions.

I'm totally stuck... I can't figure out what could be preventing the return message coming back, and I can't see what steps to take next for troubleshooting. It's not clear from the docs how a message is sent back to the framework, is there a particular host/IP/port I should be probing from EC2 to see if something is in the way? There are no outbound rules in my AWS security group that would prevent a connection, e.g. "telnet directline.botframework.com 80" succeeds.



via Gareth

Is there any mistake in new Function

I have read the Function. So I try to transform function declaration into function expression by new Function. But I am stuck in the code below:

function Foo(name, age) {
    Foo.prototype.name = name;
    Foo.prototype.age  = age;
}
var foo = new Foo(1,2); // this is ok
console.log(Foo.prototype.hasOwnProperty('name'));
console.log(foo.hasOwnProperty('name'));

However there is an error after transformation:

var Foo = new Function(['name', 'age'], 'Foo.prototype.name=name;Foo.prototype.age=age;');
var foo = new Foo(1,2); // error: Foo is not defined 
console.log(Foo.prototype.hasOwnProperty('name'));
console.log(foo.hasOwnProperty('name'));

Is there any mistake? Any answer is helpful. Thank you.

The code is right in my chrome browser. However it makes an error on platform:

  • nodejs: 6.10.0
  • win7 64bit


via gaoxinge

Socket.io event not firing

I am facing a problem while trying out a socket.io beginner's tutorial, I followed this tutorial https://socket.io/get-started/chat/

Everything seems to be okay till the very last thing, when they build a chat app, and when you hit submit in textbox, it updates the contents of the element.

I can see the messages getting printed in the node js console, but nothing in chrome's console. I also tried debugging it using developer options, but the control just never goes in this method in the index.html.

socket.on('chat message', function(msg){

Can someone please help ? I am really new to socket.io and nodejs. Thanks



via MithunS

How to create a yeoman generator without yo prefix?

I am creating a command line generator for improve productive with nodejs server development, The most widely used generator is yeoman, so I choice it for creating command line tool, But there is problem that how to use generator without yo prefix?

yo tuols

But I wanna use tuols command without yo prefix

tuols

How to do that?



via Wooden

Node vs Nodejs version

I'm trying to update node to version 7 but it is staying at v5.

2 different node versions



via joshua laver

Issue with forEach loop over array performing HTTP POST request on each object

I am using npm request module to perform super basic POST request against an API to upload image urls and get a new url link for each object within the array of urls. Once I have them I will push them back into my array.

I can't seem to make this work. I can get it working fine when I perform it over a regular string , but when I attempt to loop the http POST request over the array I cant get it to return.

I have an array for example:

var product = {
      extra_images:
        [ 'https://some.imgcdn.com/myimage1.jpg',
        'https://some.imgcdn.com/myimage2.jpg',
        'https://some.imgcdn.com/myimage3.jpg' ]
    }

product.extra_images.forEach(function(originURL, index){
          urlCloaker(originURL, extraImgResponse);
        });

Here is the function that performs the request to the API:

function urlCloaker(imgUrl, cloakedURLResponse){

  var imgUrl = 'upload=' + imgUrl;

  request('http://coolsite.com/api?' + imgUrl, function (error, response, body) {
      if(error){
        return console.log('Error:', error);
      }

      if(response.statusCode !== 200){
        return console.log('Invalid Status Code Returned:', response.statusCode);
      }
      else {
        var JSON_result = JSON.parse(body);
        cloakedURLResponse(error, JSON_result.data.img_url);
      }
  });
}

Here is my callback:

 function extraImgResponse(err, data){
      if(err)
        console.log("ERROR: " , err);
      else {
        product.extra_images.push(data);
      }

    }



via jremi

Assign values to numbers based on their coincidence with other numbers within multiple arrays

I'm creating a community app that allows its users to vote on posts similarly to sites like Reddit. I'd like to gather data that allows me to establish users' level of bias, and I'd like some direction on the implementation.

I'm approaching this problem like this:

1) Suppose each user represents a unique number, and each thread's list of users who have upvoted and users who have downvoted represent arrays respectively:

thread1 = {
    upvotes: [1, 3, 4, 10]
    downvotes: [2, 5, 8, 9]
}

2) When specific numbers tend to coincide in multiple arrays, those numbers can be said to be aligned.

//Strong alignments: 1,10; 2,8
//Weak alignments: 1,3; 3,10; 7,10; 2,5; 5,8
thread1 = {
    upvotes: [1, 3, 4, 10]
    downvotes: [2, 5, 8, 9]
}
thread2 = {
    upvotes: [1, 3, 7, 10]
    downvotes: [2, 6, 8, 9]
}
thread3 = {
    upvotes: [1, 4, 7, 10] 
    downvotes: [2, 5, 8]
}

3) Conversely, downvoting provides me with data on numbers that are maligned with each other by comparing a given thread's upvote array with its downvote array.

//Strong malignments: 1,2; 1,8; 10,2; 10,8
//Weak malignments: 1,5; 1,9; 3,2; 3,8; 7,8; 10,9
thread1 = {
    upvotes: [1, 3, 4, 10]
    downvotes: [2, 5, 8, 9]
}
thread2 = {
    upvotes: [1, 3, 7, 10]
    downvotes: [2, 6, 8, 9]
}
thread3 = {
    upvotes: [1, 4, 7, 10] 
    downvotes: [2, 5, 8]
}

I'd like to assign members to a numerical point on a spectrum between 0 and 1 based on their alignments and malignments. So, for example, if user1 becomes predictable in her voting in that when we see user3, user6 and user9 upvote a thread we can consistently guess that user1 will eventually upvote that same thread, then we can say that user1 is strongly aligned and therefore has earned a place pretty close to 0--for example, .123.

I should clarify that we know the user1 is closer to 0 and not to 1 based on her consistent malignment with user2, user4 and user12, whose downvotes typically predict an upvote from user1. In this way the assignment of 0 and 1 are arbitrary but fixed once established.

How might you implement a program that processes arrays of numbers in a way that assigns users an 'alignment' value base on their coincidence with other numbers? Solutions in Javascript or even Typescript are preferred, but this question is generally language agnostic as this process will not be integrated with the application itself. Pseudo-code is welcome.



via J. Adam Connor

Error when deploying from codeship to amazon aws

I have a local git repo and I am trying to do continuous integration and deployment using Codeship. https://documentation.codeship.com

I have the github hooked up to the continuous integration and it seems to work fine.

I have an AWS account and a bucket on there with my access keys and permissions.

When I run the deploy script I get this error: enter image description here

How can I fix the error?



via user1261710

Lock table during transaction with Knex/Postgresql

Is it possible to ask knex/bookshelf to lock a table during a transaction (in this case before an insert)? I am actually trying to add a randomly generated unique code that matches a very specific format to each entry of this table. But I know that I could face huge issues because of concurrent writings.

What basically happens is :

  • Query the db to know if this code has already been assigned to another entry
  • If not, insert it in the table

How could I proceed to disallow inserts during the entire transaction ?

Thank you in advance



via vesna

Wakeup Listener (MaxListenersExceededWarning) Node.js

I am getting the following error in my node application:

(node:245) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 wakeup listeners added. Use emitter.setMaxListeners() to increase limit
    at _addListener (events.js:260:19)
    at Connection.addListener (events.js:277:10)
    at Connection.Readable.on (_stream_readable.js:687:35)
    at Connection.once (events.js:306:8)
    at Connection._send (/mnt/app/node_modules/http2/lib/protocol/connection.js:356:10)
    at runCallback (timers.js:651:20)
    at tryOnImmediate (timers.js:624:5)
    at processImmediate [as _immediateCallback] (timers.js:596:5)

I understand what is going on in terms of this event listener is being registered more than the default max of 10 listeners. I know I could just up this number, but I am not sure if this would be fixing the problem, or just covering it up.

This is in the http2 node_module, but I don't know what is invoking it.

Here is my package.json:

{
  "name": "conciergeapp",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node --trace-warnings ./bin/start"
  },
  "dependencies": {
    "apn": "^2.1.3",
    "bluebird": "^3.5.0",
    "body-parser": "~1.15.1",
    "cookie-parser": "~1.4.3",
    "debug": "^2.6.1",
    "express": "^4.15.0",
    "jsonwebtoken": "^7.3.0",
    "mongoose": "^4.8.6",
    "morgan": "~1.7.0",
    "multer": "^1.3.0",
    "nodemailer": "^2.7.2",
    "passport": "^0.3.2",
    "passport-local": "^1.0.0",
    "passport-local-mongoose": "^4.0.0",
    "pug": "^2.0.0-beta9",
    "request": "^2.80.0",
    "socket.io": "^1.7.3",
    "socketio-jwt": "^4.5.0",
    "xoauth2": "^1.2.0"
  },
  "devDependencies": {
    "gulp": "^3.9.1",
    "gulp-autoprefixer": "^3.1.1"
  }
}



via Cheesus

What is the path variable for configuring CodeShip with Amazon?

I have a local git repo and I am trying to do continuous integration and deployment using Codeship. https://documentation.codeship.com

I have the github hooked up to the continuous integration and it seems to work fine.

I have an AWS account and a bucket on there with my access keys and permissions.

I am trying to configure my automatic deployment on codeship:

S3
AWS Access Key ID: ****************4VOA
AWS Secret Access Key: ************************************uC4j
Region: eu-west-1
Local Path: .\Users\user\Documents\projects\test
S3 Bucket: test-app-name-bucket
ACL: bucket-owner-full-control

It keeps giving me an error saying that the local path does not exist. What am I supposed to put for that field?



via user1261710

TypeError: "size" argument must be a number

I am new to javascript, and while following a tutorial I came across this code:

const fs = require ('fs')

function readCallback(err, data){
    console.log('file read')
}

function copyAll(srcFiles, dest, callback){
    for (let i=0; i < srcFiles.length; ++i){
        fs.read(srcFiles[i], readCallback)
    }
    console.log('ending copyAll')
    callback()
}

copyAll(['a.txt', 'b.txt', 'c.txt'], 'test', () => console.log('All done'))

console.log('Entering event loop')

However I get the following error message when I run the code:

C:\Users\Syed Hassaan Hasan\Desktop\Assignmnet 2 (AP)>node example.js
buffer.js:113
    throw err;
    ^

TypeError: "size" argument must be a number
    at Function.Buffer.allocUnsafe (buffer.js:140:3)
    at Object.fs.read (fs.js:658:21)
    at copyAll (C:\Users\Syed Hassaan Hasan\Desktop\Assignmnet 2 (AP)\example.js:9:6)
    at Object.<anonymous> (C:\Users\Syed Hassaan Hasan\Desktop\Assignmnet 2 (AP)\example.js:15:1)
    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)

Can somebody please tell me what am I doing wrong and what do I need to learn in order to resolve these errors?



via Hassaan Hasan

Limit each occurrence of a list by 1

I have the following query that prints out a list of numbers. I would like to limit each unique number by 1.

For example if there is three 18 in the database, it will print out 18, 18, 18, and if they are two occurrences of 5, it will print out 5,5. I only it to appear 18, and 5 in this case.

 let sqlSelectBoxInformation = "SELECT longestDimension from box ";

     connectionBoxInformation.query(sqlSelectBoxInformation, function(err, rows, fields) {

    if (!err) {
      // Check to see if the user entered hashtag is found in the database
      // Create a variable to track if the item was found


            var data = {
             rows: rows,
             userHashtag: databaseHashtag
            }
            res.render('delivery/chooseBox', data);

    }



          });



via John

Passing the JWT payload down to the express route handlers

I am willing to use JWT for my Node.js Express-based web application, and I plan to use passport-jwt to handle the user authentication and persistence.

I am somewhat new to the Passport.js and passport-jwt, so perhaps I am missing something obvious here, but I fail to see what is the suggested way how to pass the JWT payload object down to the route handlers that need to access the data stored there.

The examples of Passport.js typically show that one has to create a strategy that features the verify callback whose purpose is to find the user object and call the done(null, user), if such user can be found. This user object then is stored in req.user property that lets the route handlers to access it.

But I plan to store more information in my JWT, not just the user id: things like session state, id, ip address, etc. I need the route handlers to be able to access this other data, too, not just the identified user object.

Currently I am solving this by using a very trivial verify callback that passes the whole JWT payload object instead of just user:

const passportJWT = require("passport-jwt");
const JwtStrategy = passportJWT.Strategy;
var strategy = new JwtStrategy(jwtOptions, function(jwt_payload, next) {
  console.log('JWT payload received:', jwt_payload);
  // Skipping the user object identification here
  next(null, jwt_payload);
});

This lets me access the whole payload object from the route handlers via req.user, but it feels kind of wrong, because the req.user perhaps really should be used just for the user object.

So, what is the Passport.js-correct way to pass down extra data that can be then accessed from the route handlers down the road?



via Passiday

Trying to install Node.js and I'm receiving a curl: (77) error & failed to download resource "sqlite"

I've been dealing with this issue for a while and haven't found the proper way to deal with it yet.

I'm trying to install node.js via brew:

brew install node

I receive the following error:

==> Installing dependencies for node: sqlite, gdbm, python, icu4c
==> Installing node dependency: sqlite
==> Using the sandbox
==> Downloading https://sqlite.org/2017/sqlite-autoconf-3170000.tar.gz

curl: (77) error setting certificate verify locations:
  CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /usr/local/etc/openssl/certs
 Error: Failed to download resource "sqlite"
Download failed: https://sqlite.org/2017/sqlite-autoconf-3170000.tar.gz

Would some body in the community please clue me in on what's going on.

I'm running OS X 10.6.8, which I know can be problematic for all the updates.

I would also appreciate if someone could show me the proper way to spot duplicate installs of these directories/dependancies.



via phazzecode

Paypal Node SDK payment.execute http req - Maintaining State with multiple ec2 instances on elastic load balancing. Description?

I am about to go live with a MEAN app onto an elastic beanstalk cloud with multiple ec2 instances so I have a problem:

At the moment, I am selling tickets to events using paypal node SDK. I do my payment.create and I pass this transaction object:

transactions: [{
    amount:{
    total: req.headers.amount,
    currency:'AUD'
    },
    description:'eventID: ' + req.headers.eventid + ', userID: ' + req.headers.userid
}]

I create an associative array within my server to cache the eventid and the userid, and I used the paypal transaction ID as the key so that when paypal returns with confirmation that payment was successful I know which user and which event I need to update in my database.

If I go to cloud, if the HTTP redirect comes to a different ec2 instance this method will fail, because that associative array will be on a different machine. The ideal solution to this would be to be able to pass the eventid and userid to paypal and have them pass it back to me, is there a way to access the transaction/description data in their req callback or is there another good way to do this?



via seanEd

Use "npm start" as command to forever in .sh script

I have a .sh script in my /etc/init-d/forever to configure how forever starts and stops my Node.js app.

I wanted to start forever with the command npm start, so I can trigger my scripts from there. Is this possible?

I tried

sudo forever start --sourceDir /home/my-app -c npm start 

but its gets wrong interpreted...

info: Forever processing file: start
error: Cannot start forever
error: script /root/start does not exist.

My script so far is:

NAME=nodeapp
SOUREC_DIR=/home/nodeapp        
COMMAND="npm start"
SOURCE_NAME=index.js
USER=root
NODE_ENVIROMENT=production

pidfile=/var/run/$NAME.pid
logfile=/var/log/$NAME.log
forever=forever

start() {
    export NODE_ENV=$NODE_ENVIROMENT
    echo "Starting $NAME node instance : "

    touch $logfile
    chown $USER $logfile

    touch $pidfile
    chown $USER $pidfile

    iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
    sudo -H -u $USER $forever start --pidFile $pidfile -l $logfile -a --sourceDir $SOUREC_DIR -c $COMMAND

    RETVAL=$?
}



via Rikard

How to store/retrieve an uploaded file using GridFS, MongoDB and Node.js

I've searched through APIs for this but I can't seem to find what I need. Looking at the mongo driver API, it looks like I need to use a GridFSBucket and the stream methods. However, all the examples shown pass a filename in order to start the upload process. My question is how to do I process, store and retrieve a file that has been uploaded through an 'input type="file' form? Preferably, I want to store the buffer or typed array so I can then easily display it upon retrieval, but if that's not possible I can probably work around that.

The goal of my app is to upload PDF files, and render them in a canvas using PDFJS.Here's the code I have so far:

HTML

<html>
<head>
  <title> Test File </title>
</head>
<body>
   <input type ="file" id = "pdf_file" value = "Upload" />
   <input type ="submit" id = "submit" value = "Submit" />
   <div id="canvases" style ="position:relative;">
        <canvas id="layer" style = "z-index: 2;
            position:absolute;
            left:0px; top:0px; background-color: #00ff00; opacity:0.1"></canvas>
        <canvas id ="pdf-canvas" style=" z-index: 1; position:absolute;
        left:0px; top:0px; border:1px solid #000000;"></canvas>

  </div>
  <script src="test_annotate.js"></script>
  <script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
</body>
</html>

test_annotate.js

document.getElementById("submit").onclick = function() {

  var file =document.getElementById("pdf_file").files[0];

  console.log("new file!");
  //Step 2: Read the file using file reader
  var fileReader = new FileReader();


        fileReader.onload = function() {

              //Step 4:turn array buffer into typed array
          var typedarray = new Uint8Array(this.result);

           //Step 5:PDFJS should be able to read this
          PDFJS.getDocument(typedarray).then(function(pdf) {

            // Fetch the first page
            var pageNumber = 1;
            pdf.getPage(pageNumber).then(function(page) {
              console.log('Page loaded');

              var scale = 1.3;
              var viewport = page.getViewport(scale);

              // Prepare canvas using PDF page dimensions
              var canvas = document.getElementById('pdf-canvas');
              var context = canvas.getContext('2d');
              canvas.height = viewport.height;
              canvas.width = viewport.width;


              // Render PDF page into canvas context
              var renderContext = {
                canvasContext: context,
                viewport: viewport
              };
              var renderTask = page.render(renderContext);
              renderTask.then(function () {
                //set the annotation canvas size to match the size of the pdf
                var canvas_container = document.getElementById('canvases');
                canvas_container.style.height = renderContext.viewport.height;
                canvas_container.style.width = renderContext.viewport.width;
                var layer = document.getElementById('layer');

                layer.height = renderContext.viewport.height;
                layer.width =  renderContext.viewport.width;

              });
            });
          });

        };

//Step 3:Read the file as ArrayBuffer
fileReader.readAsArrayBuffer(file);
}

App.js

var express = require('express');
var bodyParser = require('body-parser');
var fs  = require('fs');
var mongodb = require('mongodb');
var app = express();
app.use(bodyParser.json());
app.use(express.static('frontend'))

var MongoClient = mongodb.MongoClient;
//Grid = mongodb.Grid;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
if(err) return console.dir(err);

  var bucket = new mongodb.GridFSBucket(db);
  /*What do I do here to store the uploaded file in test_annotate.js
  using mongoDB and GridFS??? */
});



via ribarcheto94

How do you install newest version of node.js on Raspberry Pi?

I want to install the latest stable version of Node.js on Raspberry Pi 3. How do I do it in such a way that a) I'm always able to update to latest version b) Can easily switch between versions



via rynop

HMAC for request body does match in Node.js

I am building some RESTful APIs using node.js. I am new to node.js. I literally 2 days ago. Here is what I am try to do.

Sending the following request using postman.

POST /register HTTP/1.1
Host: localhost:3000
Content-Type: application/json
Authorization: 415952c44ac7de13f01cdf46bac5e590f29ff12211054e16f71098ca8909652b
Cache-Control: no-cache
Postman-Token: 26087979-05c0-1d75-8822-41809272ef46

{
    "email":"a@abc.com", 
    "name": "abc xyz"
}

The value for Authorization header is computed HMACSHA256 for the request body. For testing, I used http://www.freeformatter.com/hmac-generator.html to compute HMACSHA256 and I made sure that I am using the same secret key to compute hmac.

In Node.js I am using the same request body to compute the HMACSHA256 using the following code

app.use(bodyParser.json({
    verify: function (req, res, buf, encoding) {
        console.log('json encoding: ', encoding);
        var hmac = crypto.createHmac('sha256', 'a secret');
        hmac.update(buf.toString());
        req.hasha = hmac.digest('hex');
        console.log("hmac: ", req.hasha);

        // get rawBody
        req.rawBody = buf.toString();
        console.log(req.rawBody);

    }
}));

The problem is, that gives me wrong HMACSHA256 value. It feels like something is being modified before I process the buffer. I am not sure what am I doing wrong or if there is a better way of doing it.



via Avigit

How HTTP response is generated

I'm fairly new to programming and this question is about making sure I get the HTTP protocol correctly. My issue is that when I read about HTTP request/response, it looks like it needs to be in a very specific format with a status code, HTTP version number, headers, a blank line followed by the body.

However, after creating a web app with nodejs/express, I never once had to actually write code that made an HTTP response in this format (I'm assuming, although I don't know for sure that other frameworks like ruby on rails or python/Django are the same). In the express app, I just set up the route handlers to render the appropriate pages, when a request was made to that route.

Is this because express is actually putting the response in the correct HTTP format behind the scenes? In other words, if I looked at the expressJS code, would there be something in that code that actually makes an HTTP response in the HTTP format?

My confusion is that, it seems like the HTTP request/response format is so important but somehow I never had to write any code dealing with it for a node/express application. Maybe this is the entire point of a framework like express... to take out the details so that developers can deal with business logic. And if that is correct, does anyone ever write web apps without a framework to do this. Would you then be responsible for writing code that puts the server's response into the exact HTTP format?



via dawe

How to convert a Uint8ClampedArray array into a png image in node.js?

I am using this library to read png images, but in general

https://www.npmjs.com/package/pngjs2

if I have a Uint8ClampedArray, a width and height of the array, how can I convert that and save it as a png image in node.js?

Thanks



via omega

How to send back a lot of images from node.js to client side?

I want to send 324 158x158 png images to client side from node.js. Then from client side I want to pick any of those images, and draw it on a canvas in the most efficient way. Assume I can't lazy load, and need to transfer them all together.

If it helps, they can be sent as Uint8ClampedArray arrays instead of image format.

Does anyone know how to approach this?

Thanks



via omega

how to develop simple chat app using socket.io and use mysql to store and retrieve chat history

I am trying to build a web chat app using socket.io, and I want that mysql store my chat histoy, I tried my best but was unable to find a meaningful code for this purpose

If anyone has knowledge about this please post comments.



via Fah Eem

[SOLVED]How *ngFor works with template variables in angular 2?

```
<event-thumbnail *ngFor='let event1 of events' #thumbnail  [event2]="event1" (eventClick)='handleEventClicked($event)'>Hello</event-thumbnail>
<button class='btn btn-primary' (click)="thumbnail.alertFoo()">alert id</button>
<button class='btn btn-primary' (click)='thumbnail.handleClickMe()'>click me!</button>
```

In the above code I am unable to use button using thumbnail -> template variable when using *ngFor. I also tried to wrap it inside div and still it doesnt work. It only works when I am enclosing the whole code inside a div with *ngFor i.e. also buttons which displays undesirable multiple buttons. I want to understand how ngFor works is there some work around for the above where i want events to be repeated but the buttons to be displayed only once.


via Atharva Pandey

TypeScript warning => TS7017: Index signature of object type implicitly has any type

I am getting the following TypeScript warning -

Index signature of object type implicitly has any type

Here is the code that cases the warning:

Object.keys(events).forEach(function (k: string) {

  const ev: ISumanEvent = events[k]; // warning is for this line!!
  const toStr = String(ev);
  assert(ev.explanation.length > 20, ' => (collapsed).');

  if (toStr !== k) {
    throw new Error(' => (collapsed).');
  }
});

can anyone determine from this code block why the warning shows up? I cannot figure it out.

If it helps this is the definition for ISumanEvent:

interface ISumanEvent extends String {
  explanation: string,
  toString: TSumanToString
}



via Alexander Mills

Install edge on CentOS 7

[idf@node3 js]$ mono --version
Mono JIT compiler version 4.8.0 (Stable 4.8.0.495/e4a3cf3 Wed Feb 22 18:07:20 UTC 2017)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
    TLS:           __thread
    SIGSEGV:       altstack
    Notifications: epoll
    Architecture:  amd64
    Disabled:      none
    Misc:          softdebug 
    LLVM:          supported, not enabled.
    GC:            sgen
[idf@node3 js]$ 

[idf@node3 js]$ dotnet --info
.NET Command Line Tools (1.0.1)

Product Information:
 Version:            1.0.1
 Commit SHA-1 hash:  005db40cd1

Runtime Environment:
 OS Name:     rhel
 OS Version:  7.3
 OS Platform: Linux
 RID:         centos.7-x64
 Base Path:   /opt/dotnet/sdk/1.0.1
[idf@node3 js]$ 

When I try to install edge, I get this error: fatal error: glib.h: No such file or directory

[idf@node3 react-trader]$ npm install edge

> edge-cs@1.2.1 install /home/idf/Documents/js/react-trader/node_modules/edge-cs
> node tools/install.js

MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file.
Microsoft (R) Build Engine version 15.1.548.43366
Copyright (C) Microsoft Corporation. All rights reserved.

MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file.

> edge@6.5.1 install /home/idf/Documents/js/react-trader/node_modules/edge
> node tools/install.js

make: Entering directory `/home/idf/Documents/js/react-trader/node_modules/edge/build'
  CXX(target) Release/obj.target/edge_nativeclr/src/mono/clractioncontext.o
  CXX(target) Release/obj.target/edge_nativeclr/src/mono/clrfunc.o
In file included from ../src/mono/clrfunc.cpp:4:0:
/usr/include/mono-2.0/mono/metadata/exception.h:4:18: fatal error: glib.h: No such file or directory
 #include <glib.h>
                  ^
compilation terminated.
make: *** [Release/obj.target/edge_nativeclr/src/mono/clrfunc.o] Error 1
make: Leaving directory `/home/idf/Documents/js/react-trader/node_modules/edge/build'
gyp ERR! build error 
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/lib/node_modules/npm/node_modules.bundled/node-gyp/lib/build.js:276:23)
gyp ERR! stack     at emitTwo (events.js:106:13)
gyp ERR! stack     at ChildProcess.emit (events.js:191:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
gyp ERR! System Linux 3.10.0-229.1.2.el7.x86_64
gyp ERR! command "/usr/bin/node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "configure" "build"
gyp ERR! cwd /home/idf/Documents/js/react-trader/node_modules/edge
gyp ERR! node -v v6.9.4
gyp ERR! node-gyp -v v3.4.0
gyp ERR! not ok 
ReactTrader@1.0.0 /home/idf/Documents/js/react-trader
└─┬ edge@6.5.1 
  ├── edge-cs@1.2.1 
  └── nan@2.5.1 

npm WARN ReactTrader@1.0.0 No repository field.
[idf@node3 react-trader]$ 



via Ivan

socket.io server work fine in local host but doesn't work on server

iam new in node.js and socket.io i developing sample socket.io project and i want passing argument to connection event and cordova app that connect to socket.io server

its work fine in local host but error in server i should add it, after connection event successful, supposed to post request well

i tried many solution but dosnt work

Failed to load resource: the server responded with a status of 404 (Not Found) http://37.220.11.252/socket.io/socket.io.js

GET http://37.220.11.252:3000/socket.io/?username=0912101&EIO=3&transport=polling&t=Lg_3duf net::ERR_CONNECTION_TIMED_OUT socket.io.js

on server

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var rest = require('restler');
var serverpath = 'http://37.220.11.252';
var userconnectiondata =
    {
        username: '',
        cred: '',
        socketid: ''
    }
var connectionlist = [];
server.listen(3000);

console.log("server running");

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});



io.use(function (socket, next) {


    var userconnectiondata =
        {
            username: socket.handshake.query.username,
            cred: socket.handshake.query.cred,
            socketid: socket.id
        }
    console.log('con %s', socket.id);


    connectionlist.push(userconnectiondata);

    var jsonData = {
        username: userconnectiondata.username,
        SocketID: userconnectiondata.socketid
    };

    rest.postJson(serverpath + '/Chat/UpdateSocketId', jsonData).on('complete', function (data, response) {
       // handle response
    });



    next();
    socket.on('disconnect', function (data) {

        for (var i = 0; connectionlist.length; i++) {

            if (connectionlist[i].socketid == socket.id) {
                connectionlist.splice(i, 1);
                break;
            }

        }

        console.log('discon %s', socket.id);
    });


});

in client

 <script src="http://37.220.11.252/socket.io/socket.io.js"></script>

 var temp = "username=0912101" ;
  socket = io("http://37.220.11.252:3000", {
    query: temp
     });

i appreciate any help my firends



via navid gharehkhanian

Meteor application MongoDB connection timed out

I'm running a Meteor application with Phusion Passenger as standalone meteor application with separate MongoDB. In Passenger.json I set MONGO_URL as:

"MONGO_URL":"mongodb://user:password@host:port/dbName”

I've created MongoDB in Mizrosoft Azure as NoSQL DocumentDB. When I start passenger to run the app it shows following error in the log file:

MongoError: connection 0 to HOST:10250 timed out
App 47594 stderr:     at Object.Future.wait (DIRECTORY/bundle/programs/server/node_modules/fibers/future.js:449:15)
App 47594 stderr:     at new MongoConnection (packages/mongo/mongo_driver.js:217:27)
App 47594 stderr:     at new MongoInternals.RemoteCollectionDriver (packages/mongo/remote_collection_driver.js:4:16)
App 47594 stderr:     at Object.<anonymous> (packages/mongo/remote_collection_driver.js:38:10)
App 47594 stderr:     at Object.defaultRemoteCollectionDriver (packages/underscore.js:784:19)
App 47594 stderr:     at new Mongo.Collection (packages/mongo/collection.js:99:40)
App 47594 stderr:     at AccountsServer.AccountsCommon (packages/accounts-base/accounts_common.js:23:18)
App 47594 stderr:     at new AccountsServer (packages/accounts-base/accounts_server.js:18:5)
App 47594 stderr:     at meteorInstall.node_modules.meteor.accounts-base.server_main.js (packages/accounts-base/server_main.js:9:12)
App 47594 stderr:     at fileEvaluate (packages/modules-runtime.js:197:9)
App 47594 stderr:     - - - - -
App 47594 stderr:     at Function.MongoError.create (DIRECTORY/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/error.js:29:11)
App 47594 stderr:     at Socket.<anonymous> (DIRECTORY/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/connection.js:184:20)
App 47594 stderr:     at Socket.g (events.js:260:16)
App 47594 stderr:     at emitNone (events.js:67:13)
App 47594 stderr:     at Socket.emit (events.js:166:7)
App 47594 stderr:     at Socket._onTimeout (net.js:333:8)
App 47594 stderr:     at _runOnTimeout (timers.js:537:11)
App 47594 stderr:     at _makeTimerTimeout (timers.js:528:3)
App 47594 stderr:     at Timer.unrefTimeout (timers.js:597:5)
[ 2017-03-11 20:25:57.7781 47554/7f74a99c1700 age/Cor/App/Implementation.cpp:304 ]: Could not spawn process for application DIRECTORY/bundle: An error occurred while starting the web application. It exited before signalling successful startup back to Phusion Passenger.

Is there any problem with the way I defined MONGO_URL ?



via mostafiz

Error in Login Route

I have a system set up to let user's update their password via email. Once they have updated the password for some reason passport with not authenticate the new password. They can only login with the old old. However looking in the database the password has clearly been updated. I believe there is an error in my login functionality.

router.post('/login', function(req, res, next) {
      passport.authenticate('local', function(err, user, info) {
        if (err) return next(err)
        console.log('this' + err)
        if (!user) {
          return res.redirect('/login')
          console.log('there was no user')
        }
        req.logIn(user, function(err) {
            console.log('logging in')
          if (err) return next(err);
          return res.redirect('/');
        });
      })(req, res, next);
    });



via AndrewLeonardi

Small-Meduim size multiplayer game best implementation practice with node js

I am developing a multiplayer online game with node-js and socket.io and I am wondering if I am on the right path considering implementation.

the first approach I took was like this:

  1. one app class manages logic and socket events
  2. some small model class for structure and/or database queries

but it's got pretty messy around +2k lines and I am afraid I cant debug it anymore

the second approach i have in mind is :

  • one app class
  • one class to manage socket events
  • DataModel classes that will control the game logic

or another approach :

  • sharing socket events to classes and every class manages its own events

Which one should I choose? I think I need an expert opinion. thanks in advance.



via Ashkan Ghodrat

Node.js password hash and salt questions

I'm implementing an authenticated web app and I've some questions about username and password storage.

There is no possibility of implementing any TFA method and I need some expert advice about the way I'm saving in the database the hashed password and the salt.

These are my JS functions to generate the salt and the way I hash the password:

createSalt = function() {
var len = 30;
return crypto.randomBytes(Math.ceil(len * 3 / 4))
    .toString('base64') // convert to base64 format
    .slice(0, len) // return required number of characters
    .replace(/\+/g, '0') // replace '+' with '0'
    .replace(/\//g, '0'); // replace '/' with '0'
}

hashPassword = function(password, salt) {
    var hash = crypto.createHash('sha256');
    hash.update(password || "");
    hash.update(salt || "");
    return hash.digest('hex');
}

Any comment or improvement?

Thanks in advice.



via Pablo

SaaS: protecting data from other tenants and the service

Much has been written here and elsewhere about the subject, and all this has been great food for thought. However, have not found a question which deals with our scenario specifically or indeed provides clear answers so bear with me.

Background

  • Node.js backend with multiple frontends but with the overall SaaS theme.
  • Multiple users but in the low hundreds not millions.
  • Data being held is very sesitive and its security and integrity is both a legal/regulatory concern as well as one of our key selling points against the competition.
  • Every user's schema is quite a bit different so initial plan is to settle for a a NoSQL solution like MongoDB.

The Security Ladder

  1. Level one: soft protection from other users. The bare minimum in any multi-tenant app is to ensure no user can view another user's data. This should be accomplished by the app and its Data Access Layer. (But there's always the possibility of a bug creeping in here or there and successful malicious attacks that foil all protections carefully vowen into the DAL.)
  2. Level two: hard protection from other users. In database-per-tenant strategies we have slightly better walls between users (different db connections, etc) which decreases attack surface. In our particular case this also makes sense from a document integrity point of view (each user has quite a different schema).
  3. Level three: system intrusion. Protection from attackers who manage to gain physical access to database files. Most major DBaaS provide hardware-backed disk encryption and key rotation strategies for encryption at rest so even if someone gets the files they're of limited use.
  4. Level four: SaaS intrusion. Combines database-per-tenant with encryption-at-rest where only the user holds the decryption key to prevent SaaS personnel from reading data. May sound a little extreme but some data is too sensitive to risk a dbo being able to do a casual SELECT *. A user holding and providing decryption keys for on-the-fly data decryption also helps ensure no malicious client is able to escape their sandbox and do harm to other clients' data.

Road to Encryption Heaven

Azure Table Storage offers Transparent Data Encryption but entrusts access to encryption keys to everyone who has access to the Azure portal. Hence, only Level 3.

We came across MongoDB's Encrypted Storage Engine which sounded just like what we wanted: data encrypted at rest, decrypted data resides only in memory, keys could be user-managed at a KMIP-compliant third party. However, keys are per-mongod process and would require a new mongod instance per every user. Not ideal.

Another solution we considered was something like mongoose-encryption (roughly equivalent to column encryption in SQL Server) where sensitive collections have some or all columns en/decrypted. Sounds promising but our gut feeling says it would be better to have this functionality at a database engine level and not as a DAL plugin. Moreover, it 'only' offers column-level encryption; we'd prefer encryption where it's not visible what collections reside inside a database and how many rows they have.

What Else Is There?

Having spent two days googling and asking many of the major DBaaS for help I turn to SO.

  1. Do you think we are climbing the wrong mountain? In other words, perhaps it would be more beneficial to put all business logic in a client app and have it connect to a database directly rather than go through a server-side intermediary that has temporary access to sensitive data? (But then we're not a SaaS anymore and all our assets can be downloaded.)
  2. Do you know of any database engine or provider that does not assume the app and any database admin should have unfettered access to customer data? Witnessing encryption-at-rest only now becoming a feature are we still a few years away from enabling data access strategies (almost) taking apps out of the equation and allowing users to truly protect their data?
  3. For brevity I skip the entirety of key management logistics: how users should give the app temporary access to decryption keys held by a third party, how to deal with decryption over multiple requests, etc. I realise this is a can of worms in and of itself.
  4. Apologies for the long read!


via Dav

passport js local strategy not working

    var express = require('express');
    var passport = require('passport');
    var Strategy = require('passport-local').Strategy;
    var User = require('./routes/authentication.js');

    // Create a new Express application.
    var app = express();

    passport.use(new Strategy(
      function(username, password, cb) {
        User.findByUsername(username, function(err, user) {
         if (err) { return cb(err); }
         if (!user) { return cb(null, false); }
         if (user.password != password) { return cb(null, false); }
          return cb(null, user);
        });
      })
    );

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

    passport.deserializeUser(function(id, cb) {
     User.findById(id, function (err, user) {
      if (err) { return cb(err); }
      cb(null, user);
     });
    });

    app.use(function(req, res, next) {
     res.header("Access-Control-Allow-Origin", "http://localhost:3000");
     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,      Content-Type, Accept");
    res.header("Access-Control-Allow-Credentials", true);
    next();
   });

app.use(require('morgan')('combined'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));

// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());

// Define routes.
app.get('/',
  function(req, res) {
    res.render('home', { user: req.user });
  });

app.get('/login',
  function(req, res){
    res.render('login');
  });

app.post('/login', 
  function(request, response, next) {
    console.log(request.session)
    passport.authenticate('local', 
    function(err, user, info) {
        if (!user){ response.send(info.message);}
        else {
          console.log(user);
          request.login(user, function(error) {
              if (error) return next(error);
              console.log("Request Login supossedly successful.");
              return response.send('Login successful');
          });
          //response.send('Login successful');
        }

    })(request, response, next);
  }
);

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

app.get('/checklog', function (req, res, next) {
  if (req.isAuthenticated()) {
    next();
  } else {
    res.send('login');
  }
}, function (req, res, next) {
  res.send('profile');
})
app.listen(5000);

Any help will be appreciated. The above code is not setting the cookie and because of that the req.isAuthenticated() returns false everytime. There is no problem with findbyid and findbyusername methods. sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss



via Malik Lakhani