Saturday 29 April 2017

Load web page by getting html/css/js files from an user

I need your help for a modul please, I searched on the web for answers but nothing.

The question is :

I have an dropzone/or inputs file (same idea) and I allow to user to upload one file html and several js and css (only one page) into the dropzone.

The idea is, I want to get this file and create a web page with his html/js and css and the webpage will be in the iframe.

It's like if the user can add personnalized website on my website. (his website will be only inputs, allowed him to create personalized inputs).

It's really important for me, so if you have more question don't be afraid.

I can only use html/css/js(jquery, nodejs, ...) to do this. (obligation of project)

I hope it's possible



via Erased

storing data in firebase by id but ignoring duplicates

I have a concept of a show for an app that I'm building that looks like this:

{"band":"Jimmy Herring And The Invisible Whip","date":"2017-12-08T00:00:00-08:00","numberOfShows":"1 show","venue":"Warfield, S.F.","time":"7pm/8pm","soldOut":false,"pit":false,"multiDay":false,"ages":"a/a","price":"$100"}

each show has several attributes, including one band; several rows of shows can be the same event if the datetime and venue are the same, but each show is its own object.

I want to iterate through an array of shows and store bands on firebase in a namespace called artist.

This is my code for doing that:

        for (const parsedShow of parsedShows) {
            let artistref;
            let artist;
            artistref = this.db.ref(`artist`);
            artist = await artistref.push({ name: parsedShow.band });
        }

where the node.js function is getting passed an admin-enabled db connection as db

This stores data with a topology like

artist/{id}/[name: {name}]

which I assume will work fine if I need to populate a show namespace as well that has artist ids associated with a given show (and where id is auto-generated by firebase).

My question is, how do I prevent writes to my firebase db if a given band name is already in the database? I want to enforce unique bandnames only.

Also, is there a way to incorporate an id to be generated by firebase in a ref? I'd much rather have artist/name/{name: parsedShow.band, id: <some firebase-generated id>} if that's possible.



via fox

(NodeJS) How Can I put UInt16 String directly to Buffer as writeUInt16BE?

As In Node JS buffer Like this, int 450 -> converts into 01C2 as below Image.

Buffer Input Example

I have some string with already Hex encoded String.

var a = "C2323DAD8D2D";

How Can I put this string into Buffer directly, as it looks like this?

[Buffer C2 32 3D AD 8D 2D]



via Daniel T. Lee

How to add in document scripts to Electron

I have always wanted to create my very own desktop application. And I think Electron will work best for me. I have noticed that when I render my html file into a browser window it does not load my Javascript file. Is there a correct way of doing this?

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Test App</title>
</head>
<body>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function() {
alert();
});
</script>
</body>
</html>



via Marjo Forcado

node.js twitter get tweets, nothing will load

when i run my twitter function through node, i get back no errors, but nothing will load, the twitter account is a dummy but i have 4 tweets in it and the user is @Ian_aromin, so not sure whats going on, I even replaced my code with the solution and the same thing still happens.

I am exporting my twitter key info, but I won't post it, I assume thats not the issue, because I have tried it with the code inside the same file and the same issue persists.

//function to run twitter npm
function twitter() {    
        var client = new Twitter(keys.twitterKeys);
        var params = {screen_name: 'Ian_aromin'};
//grabbing the exports api info from other .js and running a get        
        client.get('statuses/user_timeline', params, function(error, tweets, response) {
    if (!error) {
      for (var i = 0; i < tweets.length; i++) {
        console.log(tweets[i].created_at);
        console.log("");
        console.log(tweets[i].text);
      }
    }
});
}


via Christian A

Logging in User express angular with jwt

I have an app that USED to work and broke at some point and I need help fixing it please. When I submit the register form, and there is an existing user, it doesn't show the message. It also doesn't show the login success message for successful user, but it does add the user to the database.

My page login-register.html that shows two forms. Login:

<h3><i class="fa fa-sign-in"></i>  Login</h3>
            <hr />
                <div ng-if="vm.message" class="alert alert-success" role="alert">
                  <p></p>
                </div>
                <div ng-if="vm.error" class="alert alert-danger" role="alert">
                  
                </div>

                <form ng-if="!vm.isLoggedIn()" role="login" ng-submit="vm.login()">
                  <div class="form-group" ng-class="{'has-error': vm.error}">
                    <label for="username">Email</label>
                    <input type="text" class="form-control input-sm" placeholder="Username" ng-model="vm.username" autocapitalize="none">
                  </div>
                  <div class="form-group" ng-class="{'has-error': vm.error}">
                    <label for="username">Password</label>
                    <input type="password" class="form-control input-sm" placeholder="Password" ng-model="vm.password" autocapitalize="none">
                  </div>
                  <button type="submit" class="btn btn-sm btn-success">Login</button>
                </form>

and Register:

<h3><i class="fa fa-users"></i>  Register</h3>
                <hr />
                <div ng-if="vm.registerMessage" class="alert alert-success" role="alert">
                  <p></p>
                </div>
                <div ng-if="vm.registerError" class="alert alert-danger" role="alert">
                  
                </div>
                <form ng-hide="vm.message" name="register" ng-submit="vm.register()">
                  <div class="form-group">
                    <label for="name">Name</label>
                    <input type="text" class="form-control" id="name" placeholder="Name" ng-model="vm.name" autocapitalize="none">
                  </div>
                  <div class="form-group">
                    <label for="phone">Phone</label>
                    <input type="text" class="form-control" id="phone" placeholder="555-867-5309" ng-model="vm.phone" autocapitalize="none">
                  </div>
                  <div class="form-group">
                    <label for="username">Email</label>
                    <input type="username" class="form-control" id="username" placeholder="Email Address" name="username" ng-model="vm.username" autocapitalize="none">
                  </div>
                  <div class="form-group">
                    <label for="password">Password</label>
                    <input type="password" class="form-control" id="password" placeholder="Password" ng-model="vm.password" autocapitalize="none">
                  </div>
                  <div class="form-group">
                    <label for="password-repeat">Repeat Password</label>
                    <input type="password" class="form-control" id="password-repeat" placeholder="Password" ng-model="vm.passwordRepeat" autocapitalize="none">
                  </div>
                  <button type="submit" class="btn btn-success">Register</button>
                </form>

My login-controller.js (angular side):

 vm.register = function() {
        //check that passwords match
      if(vm.password != vm.passwordRepeat) {
        vm.registerError = "Passwords must match.";
        return;
      } else {
        console.log("Valid form.  Checking for existing user.");
        //check if user exists
        $http.get('/api/users/userExists', vm.username).then(function(response){
          console.log(response);
          if(response.message == true) {
            vm.registerError = "A user with that email address already exists.";
            return;
          } else if(response.message == false) {
            //create user object to send to server
            var user = {
              username: vm.username,
              password: vm.password,
              name: vm.name,
              phone: vm.phone
            };
            $http.post('/api/users/register', user)
            //success message
            .then(function(result){
              console.log(result);
              vm.registerMessage = "Registration success!  Please login.";
              vm.user = result.user;
              return;
            }, function(error){
              console.log(error);
              vm.registerError = [];
              for(var i=1; i<error.data.errors.length; i++){
                vm.registerError.push(error.data.errors[i]);
                return;
              }
            });
          }
        }, function(error){
          console.log(error);
          vm.registerError = error;
          return;
        });
      }
  };

My API users.controller.js (node side): CHECK IF USER EXISTS FUNCTION

module.exports.userExists = function(req, res) {
  var username = req.params.username;
  console.log('Check if ' + username + ' exists.');
  //see if user exists in db and return true or false
  User
    .findOne({username: username})
    .select('username')
    .exec(function(err, user) {
      console.log("find user result");
      if (err) {
        console.log("Server error",err);
        res.status(500).json({error: err});
      } else if(!user) {
        console.log("User not found in database", username);
        res.status(200).json({message: false});
      } else {
        // send TRUE for userExists
      res.status(200).json({message: true, user: user});
      }
    });
};

REGISTER FUNCTION

module.exports.register = function(req, res) {
  console.log('registering user');
  //create the user object with hashed pass
  var user = {
    username: req.body.user.username,
    name: req.body.user.name,
    phone: req.body.user.phone,
    password: bcrypt.hashSync(req.body.user.password, bcrypt.genSaltSync(10))
  };
  console.log("User",user); //log the hashed user info
  //save user to db
  User.create(user, function(err, user) {
    if (err) {
      console.log(err);
      //send error message back
      res.status(400).json({err: err, error: err.message});
    } else {
      //send user and success message back
      console.log('user created', user);
      res.status(201).json({user: user, message: "Registration success!  Please login."});
    }
  });
};

And, of course, my auth routes for the API:

//Authentication routes
router.route('/users/register').post(ctrlUsers.register);
router.route('/users/login').post(ctrlUsers.login);
router.route('/users/userExists').post(ctrlUsers.userExists);



via user3561890

holedata is not defined while loading ejs file after res.render

I am inserting the data into mongodb and then page rendering to success.ejs. In the success.ejs file I gave one link. When click link in the same success.js file data should fetch from mongodb and show in same success.ejs file. But before loading the success.ejs file after post the data in the console showing holedata is not defined error message.

My post data part in index.js file

app.post('/signingin', function(req, res) {
      var item = {
        name: req.body.name,
        title: req.body.title,
        age: req.body.age
      };
      mongo.connect(url, function(err, db){
        assert.equal(null, err);
        db.collection('satyamsoft').insertOne(item, function(err, result){
          assert.equal(null, err);
          console.log('item inserted');
          db.close();
        });
      });
        res.render('pages/success');
        //console.log(req.body);
    });

My success.ejs page

!DOCTYPE html>
<html lang="en">

    <% include ../partials/head %>
    <title>Post Jobs | Spyeer</title>
    <body>

        <% include ../partials/nav %>       
        <section class="get">
          <h2>Data Inserted</h2>
          <a href="/getdata">Get Data</a>
          <div>
            <ul>
                <% holedata.forEach(function(data) { %>
                    <li><%= data.this.name %> - <%= data.this.title %> - <%= data.this.age %></li>
                <% }); %>
            </ul>
          </div>
        </section>

        <% include ../partials/footer %>

        <% include ../partials/scripts %>

    </body>
</html>

get part code in index.js file

app.get('/getdata', function(req, res){
      var resultArray = [];
      mongo.connect(url, function(err, db){
        assert.equal(null, err);
        var cursor = db.collection('satyamsoft').find();
        cursor.forEach(function(doc, err){
          assert.equal(null, err);
          resultArray.push(doc);
          //console.log(resultArray);
        //res.render('pages/getdata', {holedata: resultArray});
      }, function(){
        db.close();
        res.render('pages/success', {holedata: resultArray});
      });

Please help me advance thanks.



via Satyam

how to round the value with math.round

I am trying to round the value from 8904000 to 8900000 is there any possible way to change this using Math.round. example in MS Excel =round(8904000,-5); ANS: 8900000 I TRIED LIKE THIS BUT NOT WORK Math.round(8904000,-5); ANS: 8904000 i need it in Math.round(?)



via yousuf

node.js: req.next is not a function

I've tried to deploy the project to google cloud platform. The code is working fine on my local machine. However, I'm getting the following error on gcloud.

TypeError: req.next is not a function
at done (/app/node_modules/express/lib/response.js:955)
at tryRender (/app/node_modules/express/lib/application.js:641)
at EventEmitter.render (/app/node_modules/express/lib/application.js:591)
at ServerResponse.render (/app/node_modules/express/lib/response.js:960)
at (/app/routes/posts.js:15)
at tryCatcher (/app/node_modules/mongolass/node_modules/bluebird/js/release/util.js:16)
at Promise._settlePromiseFromHandler (/app/node_modules/mongolass/node_modules/bluebird/js/release/promise.js:510)
at Promise._settlePromise (/app/node_modules/mongolass/node_modules/bluebird/js/release/promise.js:567)
at Promise._settlePromise0 (/app/node_modules/mongolass/node_modules/bluebird/js/release/promise.js:612)
at Promise._settlePromises (/app/node_modules/mongolass/node_modules/bluebird/js/release/promise.js:691)
at Async._drainQueue (/app/node_modules/mongolass/node_modules/bluebird/js/release/async.js:138)
at Async._drainQueues (/app/node_modules/mongolass/node_modules/bluebird/js/release/async.js:148)
at Immediate.Async.drainQueues (async.js:17)
at runCallback (timers.js:666)
at tryOnImmediate (timers.js:639)
at processImmediate (timers.js:611)

routes/posts.js:

router.get('/', function(req, res, next) {
  var author = req.query.author;

  PostModel.getPosts(author)
    .then(function (posts) {
      res.render('posts', { //line 15
        posts: posts
      });
    })
    .catch(next);
});

getPosts function:

getPosts: function getPosts(author) {
    var query = {};
    if (author) {
      query.author = author;
    }
    return Post
      .find(query)
      .populate({ path: 'author', model: 'User' })
      .sort({ _id: -1 })
      .addCreatedAt()
      .addCommentsCount()
      .contentToHtml()
      .exec();
  },



via rluo

How to generate swagger paths based on model definition?

I want to generate swagger schema based on my json model.

Currently am using https://www.npmjs.com/package/generate-schema to generate the definitions which works fine, but is there anything like that that I can generate the paths ?

I just need a sngle path with put/get/delete actions for each of my definition.



via sreginogemoh

How do we use Async, and what is the best way in nodeJS

I'm trying to pass a query to my database, then send the result to my client side, but it's looking like the request is async, because my request happen after that my post request return the value, so the question is how do I set an await for request?

here's a sample of my code!

my database connection

var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password : 'my_password',
database : 'MEETME'
});

connection.connect(function(err){
    if(err){
    console.log("error while connecting to database");
    console.log(err.code);
    }
});

//function that query database <-------

function queryDatabase(userQuery){
       connection.query(userQuery, function(err, result){
            if(err){
           throw err;
        }
       console.log("before");
        return result;
    }); 
}

and this is my post request

//POST
app.post('/signin', function(request, response){
    var query = queryDatabase("SELECT EMAIL FROM MEMBER WHERE ID_MEMBER = 3");
    console.log(query);
    console.log("after");
    response.end(query, 200);
});

the result in the console is:

undefined
after
before



via MathieuAuclair

Difficulties with OpenShift as a Production environment

I develop nodejs backend code using Cloud9, push to GitHub. Testing is all well on my dev Cloud9 environment. When I push the release to OpenShift as my production environment, OpenShift indicates success on push and start. However, get errors when my client connects via socket.io to OpenShift. OpenShift is returning (a non-traceable) HTML page of 'Internal Error' when client connects using socket.io. Any suggestions?



via PotOfCoffee2Go

TS2307: Cannot find module 'express'

I am just getting started with TypeScript and I am not sure why I am seeing this error in my IDE(Webstorm).

"TS2307:Cannot find module 'express'"

import express = require("express"); 

I have uninstalled/installed back the typescript globally and still see the error. I used the following tutorial as a starting point http://www.vandiest.biz/?p=3931

Currently, I am blocked and not sure how to proceed forward with this solution. Also I have tried recommendations on some other posts regarding the same error, but with no luck.



via RRP

how to break in middleware in expressjs

I have a MEAN stack based web application and I have a middle ware which validates the request for some authorization purpose.. I have written the security checking part..but if the user is unauthorized , the express middle ware should stop execution and return back user 401 status with a message.. How can I achieve it? I tried to to use return statement in middle ware ;but its not working. Though some of them works , it throws exception and breaks the server . I want just an abrupt ending to the request. Any help will be appreciated.



via Jocket

NodeJS incorrect values

From my experience, php code and javascript one can be very portable, but today I found this:

$secret1 = 8992483;
$secret2 = 1785665;
$counter = 3288985389;
for ($i=0; $i<10000000; $i++) {
    $counter = ($counter * $secret1) % $secret2;
}
console.log($counter);

when executed in chrome/nodejs i get 652751, but in other languages like PHP or even C it shoud be: 1281709

What am I doing wrong? :S

Thanks



via Marcos Fernandez Ramos

Jasmine Unit Testing Angularjs

I'm new to Unit Testing. I have followed the tutorials and I have everything configured on node.js via npm. I have done some describe and it just to get the feel for ho things are set up and my spec runner is fine. The problem I'm trying to get test on controllers figured out but I run in a snag and been trying to figure things out for a while but I continue to get the same error so I thought I would reach out.

I'm trying to do a simple test on a LoginController but I continue to get the same error. I can't point out what I'm doing wrong. Trying to get over this hurdle.

TypeError: angular.mock.module is not a function:

spec runner index html file.

<!doctype html>
   <html>
 <head>
<title>Jasmine Spec Runner</title>
<link rel="stylesheet" href="../bower_components/jasmine-core/lib/jasmine-core/jasmine.css">
</head>
<body>
<script src="../My Documents/My Website/AngularLogin-
      Registration/js/angular-1.6.0.js"></script>
<script src="../My Documents/My Website/AngularLogin-Registration/js/angular-route-1.6.0.min.js"></script>

<script src="../bower_components/jasmine-core/lib/jasmine-core/jasmine.js"></script>
<script src="../bower_components/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
<script src="../bower_components/jasmine-core/lib/jasmine-core/boot.js"></script>

<!-- include source files here... -->


<!--<script src="//code.jquery.com/jquery-3.1.1.min.js"></script>-->
<!--<script src="//code.angularjs.org/1.6.0/angular-cookies.min.js"></script>-->
<script src="../My Documents/My Website/AngularLogin-Registration/js/angular-mock.js"></script>
<script src="../My Documents/My Website/AngularLogin-Registration/js/app.js"></script>
<script src="../My Documents/My Website/AngularLogin-Registration/login/login.controller.js"></script>

<!-- include spec files here... -->
<script src="spec/test.js"></script>

Here is my test file.

describe('LoginController test', function () {
    beforeEach(angular.mock.module('app'));
    beforeEach(angular.mock.inject(function(_$controller_){
        $controller = _$controller_;
}));
describe('$scope.grade', function() {
      it('sets the strength to "strong" if the password length is >8 chars', 
       function() {
        var $scope = {};
        var controller = $controller('LoginController', { $scope: $scope });
  $scope.password = 'longerthaneightchars';
  $scope.grade();
      expect($scope.strength).toEqual('strong');
    });
       });
          });

Thanking You In Advance PDH



via user2280852

error when using pusher in nodeJS

I'm new to Node.JS. and I intended to build a realtime chat room with pusher. I follow the tutorial in website of Pusher "Making ReactJS Realtime With Websockets" https://blog.pusher.com/making-reactjs-realtime-with-websockets/ the difference is I use nodeJs as backend server, I get error as "pusher.js:372 WebSocket connection to 'wss://ws.pusherapp.com/app/[object%20Object]?protocol=7&client=js&version=4.1.0&flash=false' failed: Error during WebSocket handshake: Unexpected response code: 502"

and errors "XMLHttpRequest cannot load http://sockjs.pusher.com/pusher/app/[object%20Object]/417/cqqjmnm0/xhr?protocol=7&client=js&version=4.1.0&t=1493516587238&n=24. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access. The response had HTTP status code 404."

and here is my Main.js which connect the Pusher and should be able to receive message

constructor(props) {
    super(props);
    this.state = {messages: []};
    this._onMessage = this._onMessage.bind(this);
}

componentWillMount() {
    this.pusher = new Pusher({
        appId: '',
        key: '',
        secret: '',
        encrypted: true
    });
    this.chatRoom = this.pusher.subscribe('messages');
}

componentDidMount() {
    this.chatRoom.bind('new_message', function(message){
        this.setState({messages: this.state.messages.concat(message)})
    }, this);
}

_onMessage(e) {
    if (e.nativeEvent.keyCode !== 13) return;

    let input = e.target;
    let text = input.value;

    // if the text is blank, do nothing
    if (text === "") return;

    let message = {
        username: this.props.username,
        text: text,
        time: new Date()
    };

    let request = new Request('http://localhost:3000/notification', {
        method: 'POST',
        cache: false,
        context: message
    });

    fetch(request).then(function(response) {
        if(response.status === 200) {
            console.log("success");
            input.value = "";
        }
        else console.log("fail");
    })
}

and this is my Node.js server router.post('/notification', function (req, res, next) {

let pusher = new Pusher({
    appId: '333442',
    key: 'f4a5f819abf18922c4e7',
    secret: 'bbf4266f4f9469e04653',
    encrypted: true
});

pusher.trigger('messages', 'new_message', {
    "message": "hello world",
});

res.status(200);

});

what happen is I can see res.status(200) in my console but I can't receive message from pusher.

and I have include following in my index.html

  <script>

      // Enable pusher logging - don't include this in production
      Pusher.logToConsole = true;

      var pusher = new Pusher('', {
          encrypted: true
      });


      var channel2 = pusher.subscribe('messages');
      channel2.bind('my-event', function(data) {
          alert(data.message);
      });
  </script>

Anyone has the same problem? I'm confused about the reason that I cannot receive message from Pusher



via Qi Lyu

Azure App Service on Linux plan encoding issue

I deployed a node app "typically prerender server" to two different places and tested prerender with a get request to a url contains Arabic letters

1. Heruko: working perfectly

2. Azure App Service on linux plan failed with HTTP Error 400. The request URL is invalid.

here is the respond body from Postsman

<html>
    <head>
        <title>Bad Request</title>
        <meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
        <style type="text/css">.cf-hidden { display: none; } .cf-invisible { visibility: hidden; }</style>
    </head>
    <body>
        <h2>Bad Request - Invalid URL</h2>
        <hr>
        <p>HTTP Error 400. The request URL is invalid.</p>
    </body>
</html>

Notice that the response head/meta contains charset=us-ascii

here is how the prerender node app see part of the url

u008aÙ\u0088Ù\u0085_Ù\u0085Ù\u0083رÙ\u0088Ù\u0086ع 

i even created a node docker image to set language and locale to en_US.UTF-8 and changed Azure App to use this Docker image but still get error.

Any help please ?!



via Abou-Emish

Loading Static Files w/ Node.js only kind of working

I am new to using node/express and am just practicing to make sure I know how everything fits together. I was trying to get a simple html page with very simple css styling from the server using express, but I was running into some problems I haven't been able to solve.

This is the outline of my files for the projects: 1) "Name" is the file that hold all of these:

  -node_modules
  -public
      -style.css
  -app.js
  -index.html
  -package.json

Here is my code from my app.js file:

'use strict';
const express = require('express');
const app = express();
const path = require('path');

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

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

const server = app.listen(3000, () => console.log('listening on port 8080'));

If I type localhost:3000/style.css in the browser, the css file text shows up fine but when I type localhost:3000/ to get my index.html rendered with css, the network table in developer tools gives me a 404 saying it can't find my css document. I'm wondering if anyone knows why this is? Thanks!!!



via FlBloo

Trouble with a basic node.js transform stream

I'm learning nodejs right now and am trying to set up a simple transform stream. The code I am creating is similar to a few tutorials - but I keep getting errors. Right now I am just trying to pass data directly though with no changes (I've removed some commented out lines for brevity):

newstream.js:

var fs = require('fs');
var makeBig = require('./makeBig');

var myReadStream = fs.createReadStream(__dirname + '/Sample.txt');
var myWriteStream = fs.createWriteStream(__dirname + '/WriteMe.txt')

myReadStream
.pipe(makeBig)
.pipe(myWriteStream);

makeBig.js:

const Transform = require('stream').Transform;
const makeBig = new Transform({
        transform(chunk, encoding, callback){
        //chunk = chunk.toUpperCase();
        //console.log(chunk);
        this.push(chunk);
        callback();
    }
});

makeBig.js follows the 'Simplified Constructor Approach' form described in NodeJS v7.9.0 documentation.

Here are the errors that I get:

$ node newStream.js 
_stream_readable.js:501
  dest.on('unpipe', onunpipe);
       ^

TypeError: dest.on is not a function
    at ReadStream.Readable.pipe (_stream_readable.js:501:8)
    at Object.<anonymous> (/home/thodges/Workspace/Node/streams/newStream.js:15:2)
    at Module._compile (module.js:571:32)
    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:420:7)
    at startup (bootstrap_node.js:139:9)



via Thomas Hodges

Unirest request in Node.js

I am quite new to javascript and Node.js, and I came because I want to make a Discord bot for people playing card games. I am using the discord.js-commando libraries.

I kinda need a 'complete guide' at this. I'd like to know more about requesting information from a Mashape API with Unirest (specifically this one (hearthstone)), how the parameters work, how do I parse a JSON file for a response and a couple examples with this API (my main goal is to get the image URL of a card).

Here is the code of the command I am coding:

const commando = require('discord.js-commando');

class HSCommand extends commando.Command {
    constructor(client) {
        super(client, {
            name: 'hs',
            group: 'cards',
            memberName: 'cards',
            description: "Fetches the image of an Hearhtstone card and posts its details in the chat"
        });
    }

    async run(message, args) {
        if (message.author.bot) return;

        var requestcardname = args;
        var url = 'https://omgvamp-hearthstone-v1.p.mashape.com/cards/search/' + requestcardname;
        var requesturl = url.replace(" ", "%20");
        console.log(requesturl);


via jsgarden

Unity 3D 'Vuforia with Log-in/Sing-up/Sessions process

I've been searching a way to create users and a log-in proccess in Unity 3D by sending that data to a web service (API rest created in Sails.js/node.js ). In the case of Log-in process I would like to retrieve a session which will say that the user is connected and as a result getting access to the Vuforia app' capabilities like making GET requests to specific actions that only logged-in Users can in my Node.js API webservice.

Finally; I've used WWW and WebRequest class to make some request from Unity but that would mean that I should open the APIrest(webServices) to everyone without the session's process. And the last thing I came up; is to use Sockets but I don't know how this approach would work form me.



via superkiller170793

Exclude option vs. Entry Point in Webpack

If you have an entry point in Webpack, doesn't that mean Webpack will only bundle up and transform the files that are in that entry point or required by that entry point? That would then automatically negate or exclude the files that aren't required by that entry point file, correct? Why do you still need an exclude option in the loader config for the files in your node_modules? That isn't required in your entry point so I thought webpack would ignore those files altogether, or is there some magic I'm missing? If you don't have the exclude option, will loaders automatically just try to transform all your files in your project?



via mangocaptain

localhost recognizes .env file in my node.js sever but not on ubuntu

ok, so I hid a password in my node.js server using a .env file

const env = require('dotenv').config();
var pass = {
  password: process.env.PASS
};

It works perfectly and I can sign in to my admin portal on my localhost but I can't on the site hosted on ubuntu. I triple checked to make sure that the dotenv npm was downloaded on ubuntu and that my mongo database has the correct username and password in ubuntu. Is there another reason why its not working?



via Dominic Zenon

Why wouldn't you want to use the `--save` option for npm install?

I read about using the --save option here and and it says that it will add the installed package to your package.json file. But why isn't this automatic? Wouldn't you always want this? My understanding is that the node_modules is the directory that actually holds the code of your package and package.json is the reference/list of all the packages you have installed so that when you push it up to a repo, you only push the latter up and not the former, to save space. Then when other people clone or fork off your repo, they will have the package.json to reference and install all the necessary packages to work off of your project. Thus, wouldn't you always want your packages to be in the package.json in order for everyone to get what is needed?



via stackjlei

Mongoose find all posts and get the hottest categories

i have this problem where i need to find the hottest categories from all the posts that i've search.

This is my POST schema model

var PostSchema = new mongoose.Schema({
    maincategory: String,
    subcategory: String,
    quantity: String,
    budget: Number,
    name: String,
    description: String,
});


PostSchema.index({name: 'text', description: 'text'});

So what i need to do is, crawl to all the posts, check their main category and sub category, then after crawling to all posts and get their categories, i need to count on how many posts on this categories then sort out the categories where i will show the categories which has the highest amount of posts. Then i will show which categories are the hottest, maybe top 5

Thank you!



via John

Problems migrating project to Webpack 2

I was trying to set up webpack-dev-server but I kept getting errors that required me to update webpack. I ran npm install --save-dev webpack@2.4.1in my root directory to update Webpack, but I get this error when trying to run node_modules/.bin/webpack-dev-server as well as node_modules/.bin/webpack:

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.resolve has an unknown property 'root'. These properties are valid:
   object { alias?, aliasFields?, cachePredicate?, descriptionFiles?, enforceExtension?, enforceModuleExtension?, extensions?, fileSystem?, mainFields?, mainFiles?, moduleExtensions?, modules?, plugins?, resolver?, symlinks?, unsafeCache?, useSyncFileSystemCalls? }
 - configuration.resolve.extensions[0] should not be empty.

I know of the migration guide and I applied what I thought was needed to my project but I don't know what I'm missing. This is my webpack.config.js :

const path = require('path');

module.exports = {
  context: __dirname + "/app",

  entry: {
    javascript: "./js/app.js",
    html: "./index.html",
  },

  output: {
    filename: "app.js",
    path: __dirname + "/dist",
  },

  resolve: {
    extensions: ['', '.js', '.jsx', '.json'],
    root: path.resolve(__dirname, './app/js'),
  },

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, "app")
        ],
        loaders: ["react-hot", "babel-loader"],
      },
      {
        test: /\.html$/,
        loader: "file?name=[name].[ext]",
      }
    ],
  },
}

My package.json looks like:

{
  "name": "AAA",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js --hot --inline --history-api-fallback"
  },
  "devDependencies": {
    "babel-core": "^6.21.0",
    "babel-loader": "^6.2.10",
    "babel-preset-es2015": "^6.24.0",
    "babel-preset-react": "^6.16.0",
    "eslint": "^3.13.1",
    "eslint-config-airbnb": "^14.0.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^3.0.2",
    "eslint-plugin-react": "^6.9.0",
    "file-loader": "^0.9.0",
    "react-hot-loader": "^1.3.1",
    "react-router": "^3.0.2",
    "webpack": "^2.4.1",
    "webpack-dev-server": "^1.16.2"
  },
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2"
  },
}

How can I fix this error to launch the dev server and use webpack?



via feners

share node.js modules across React apps?

I'm trying out node.js and npm for the first time, to code a React tutorial using the Create React App boilerplate.

The first simple app is working fine.

The file structure looks like this (Windows 7):

file structure of node.js app created with the Create React App boilerplate

My concern is that the node_modules folder is 70mb on file and occupies 120mb on the disk.

It seems that each time I create a new app via Create React App, the same folder is going to get re-created for the new app, and occupy a similar vast amount of storage.

My question is: is there some way to create new apps such that the same modules are not downloaded and don't end up occupying more and more storage, and can instead be shared across apps (not sure if node.js philosophy supports sharing of such modules).



via user1883050

CasperJS moving jQuery UI draggable item

I am trying to crawl some data from the web page and I need to move draggable item to droppable place. This is what I've tried so far:

var casper = require('casper').create();
var mouse = require('mouse').create(casper);

casper.start("https://uygulama.gtb.gov.tr/BeyannameSorgulama/",function() {
    this.sendKeys('input[id="txtBeyannameNo"]', '17341200EX119337');
    this.mouse.down('li.ui-draggable');
    this.mouse.move('#ajax-fc-circle');
    this.mouse.up('#ajax-fc-circle');
});

casper.then(function(){
    casper.capture('screenshots/test.png');
    this.click('input[id="btnSorgula"]');
});

casper.waitForSelector('span[id="LabelDurum"]', function (){
    casper.capture('screenshots/test2.png');
    console.log("OK!");
});

casper.run();

But I cannot manage to finish the process successfully.

What am I doing wrong?



via Barış Çağan Kurtuluş

(JavaScript) data.split('\n') is not a function

I am trying to make a random string picker with a text document that splits at every line.

However, when I try to run it, it says that data.split is not a function.

fs.readFile('list.txt', function(err, data){
        if(err) throw err;
        var lines = data.split('\n');
        var rand = [Math.floor(Math.random()*lines.length)];
        var rlist = lines[rand]
})



via Revin Bray

Express route not going to expected handler

I have two routes set up as follows:

router.get('/users', (req, res) => {});

and

router.get('/users/:id', (req, res) => {});

The second route works as expected. It's intended to request a single user object by ID. I intended the first route to return all users. However, if I don't pass an id parameter to the route, express is still routing the request to the second route, just without the id parameter set. Is there any way to get it to go to the first route handler, or do I just have to use only the second route, and check for the existence of the id parameter to determine which results to return?



via Jedediah

ProcessData Node.js stin/stdout) issues

Having a bit of trouble understanding how to run my code using a ProcessData wrapping function on hackerrank (node.js). It seems I can't drop a function with the parameters I have in the ProcessData wrapper without getting back ~no response on stdout~. How do I pass their input (a string of integers) in to my function and get a response of some sort so I can debug? Help would definitely be appreciated. Please see my function, the coding environment, the input & expected output below. Thanks!

    /*

     Input Format

    The first line contains two space-separated integers 
denoting the respective values of  (the number of integers) 
and  (the number of left rotations you must perform). 
    The second line contains  space-separated integers 
describing the respective elements of the array's initial state.

    */

/*Environment with my code, below (how do I pass input as an argument to this function?? 
console.log or return the data, and get a response for debugging?)*/

function processData(input) {
    //Enter your code here
    var rotate = function(num,turns,ar){
    var store = ar.slice(0, turns);
    for(var i=0; i<store.length; i++){
        ar.shift();
        ar.push(store[i]);
    }
    return ar;
};
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});



via jb07

Making a Regex pattern Javascript

I can kind of read regex but building a pattern is out of my capability at the moment, I am building a Discord Bot and I need to check if a message includes emoji s. Emoji s in Discord look like :emoji:, I tried checking if the message includes a colon : but as it turns into an emoji, it didn't recognize it. I am using the Discord.js library if that matters.



via Rusty

Running into EMFILE error when using jsmediatags

I use jsmediatags to read a tags of a huge amount of files (>20.000). My code throws an EMFILE Error (ERROR fs Error: EMFILE: too many open files, open "path-to-file") because I exceed the maximum amount of open files. I cannot use anything like graceful-js, because fs is built into the module. So my question is: How do I avoid the EMFILE error?

I can think of 2 ways: Using something to read only batches of data at once or somehow replacing the fs dependency with graceful-js. It would be very helpful if somebody could point me in the right direction.

var addToDatabase = (files) => {
    for(let i=0;i<files.length;i++){
        if(files[i].endsWith(".mp3")){
            new jsmediatags.Reader(files[i])
            .setTagsToRead(["title", "track", "artist", "album", "year"])
            .read({
                onSuccess: function(tag) {
                    database.insert({path: files[i], title: tag.tags.title, track: tag.tags.track, artist: tag.tags.artist, album: tag.tags.album, year: tag.tags.year});
                },
                onError: function(error) {
                    console.log("ERROR", error.type, error.info, files[i]);
                }
            });
        }
    }
}

require('node-dir').files(_some_dir, function(err, files) {
    if (err) dispatch(rebuildDbRejected("ERROR while reading the database directory"));
    addToDatabase(files);
});



via Nash

Cloudinary api - resolve promise

I want to write a function that returns a Boolean indicating whether an image with the specified public_id already exists in my Cloudinary space.

I can log the result to the console with the following code:

function isUploaded(public_id) {
  cloudinary.api.resource(public_id, function(response){
    console.log(response.hasOwnProperty('public_id'));
  });
};

isUploaded('test');

However, I want to pass on the result, the Boolean, to another function. Using a return statement results in { state: 'pending' } being logged:

function isUploaded(public_id) {
  return cloudinary.api.resource(public_id, function(response){
    return response.hasOwnProperty('public_id');
  });
};

console.log(isUploaded('test'));

This is has something to do with javascript Promises. I can't seem to restructure my code to make it work though. Any help would be much appreciated.



via The Dancing Code

Method not working from created hook Vue.js

I am trying to create a web app based on a database. Setup: NodeJS and a Vuejs 2 app generated with the CLI (with Webpack). Currently, I am using axios to retrieve records into an object. Based on that object I want to draw some svg lines from certain points to other points. The method works completely as designed when running it from an @click (v-on directive). However, when I try to add it to the created hook it doesn't work. No errors displayed. It's just not running. Does anyone no why? Code example below.

<template>
<div class="holder">
  <step v-for="item in steps"></step>
  <events v-for="point in points"></events>
  <button @click= "createArrows">Test</button>
</div>
</template>

<script>
import axios from 'axios'
import Step from './Step.vue'
import Events from './Events.vue'

export default {
name: 'Graph',
data () {
  return {
    steps: '',
    events: '',
    points: []
},

components: {
  Step, Events
},
methods: {
  getSteps: function() {
    let getsteps = this
    axios.get('localhost:8000/api/steps')
          .then(function (response) {
            getsteps.steps = response.data
          })
          .catch(function (error) {
            getsteps.steps = "Invalid request"
          })
  },
  getEvents: function() {
        let getevents = this
        axios.get('localhost:8000/api/events')
              .then(function (response) {
                getevents.events = response.data
              })
              .catch(function (error) {
                getevents.events = "Invalid request"
              })

    },
  createArrows: function() {
    let targetids = []
    let sourceids = []
    for (let i = 0; i < this.events.length; i++) {
      targetids.push(this.events[i].target_id)
      sourceids.push(this.events[i].source_id)
    }

    let stepids = []
    let tops = []
    let lefts = []
    for (let i = 0; i < this.steps.length; i++) {
      stepids.push(this.steps[i]._id)
      tops.push(this.steps[i].top)
      lefts.push(this.steps[i].left)
    }


    const blockwidth = 300
    const blockheight = 110
    const margin = 20
    let idx = 0
    let sourcelocX = 0
    let sourcelocY = 0
    let targetlocX = 0
    let targetlocY = 0

    for (let i = 0; i < this.events.length; i++) {
      idx = stepids.indexOf(sourceids[i])
      sourcelocX = Number(lefts[idx]) + Number(blockwidth)
      sourcelocY = Number(tops[idx]) + 0.5 * Number(blockheight)
      idx = stepids.indexOf(targetids[i])
      targetlocX = Number(lefts[idx])
      targetlocY = Number(tops[idx]) + 0.5 * Number(blockheight)
      let line = sourcelocX+ ',' + sourcelocY + ' ' +
                (sourcelocX+margin) + ',' + sourcelocY + ' ' +
                (targetlocX-margin) + ',' + targetlocY + ' ' +
                targetlocX + ',' + targetlocY
      let triangle = (targetlocX-10) + ',' + (targetlocY-7) + ' ' +
                      (targetlocX-10) + ',' + (targetlocY+7) + ' ' +
                      targetlocX + ',' + targetlocY
      this.points.push([line,triangle])
    }
  },
created() {
  this.getSteps(),
  this.getEvents(),
  this.createArrows()
}


}



via Imre_G

Create and connect to different websocket paths

We are using the ws library from https://github.com/websockets/ws as our server. Currently we have the server such as this where everyone connects to port 192.68.1.1:8080 and everyone deals within this context:

var WebSocketServer = require('ws').Server;
wss = new WebSocketServer({port: 8080});

wss.on('connection', function (ws) {
    ws.on('message', function (message) {
        console.log('received: %s', message);
        ws.send('We got your message!', function ack(error) {
            // If error is not defined, the send has been completed, otherwise the error
            // object will indicate what failed.
            if(error){
                console.log('Some error occured ' + error);
            }
        });
    });
});

We would like to have different paths available so that users can connect to different paths. E.g

ws://192.68.1.1:8080/space1
ws://192.68.1.1:8080/space2
ws://192.68.1.1:8080/space3

We know socket.io has something similar to this in terms of namespaces. We are looking to implement a feature like this (but due to other modules and architecture of the project we have to use the ws library and can't use socket.io).

Our goal that we are trying to accomplish is to have certain users only be able to communicate with certain users like in a group chat scenario. We want the user to connect to a unique room and be able to chat with all the members there.

Is there a method using this library to accomplish something similar?



via user2924127

How to configure CouchDB/PouchDB from my nodejs app

I'm trying to create a self-hosted app. This app would provide a custom express server with some routes and also provides a CouchDB access using pouchdb-server. I would like the node server to be able to configure the database and create the admin username/password, and then create the roles functions. How can I configure CouchDB from my nodejs app?



via Vinz243

Load native C modules in duktape 2.1.0 to

I am still lost after reading the how-to article.

It is said that

The load callback is a Duktape/C function which takes the resolved module ID and: (1) returns the Ecmascript source code for the module or undefined if there's no source code, e.g. for pure C modules, (2) can populate module.exports itself, and (3) can replace module.exports.

But when loading a native C module,

  • what should be pushed into the value stack? duk_push_undefined(ctx) instead of duk_push_string(ctx, module_source)?
  • what should be returned by the load callback to its caller? return 0 instead of return 1?

I tried to call myobject_init (using the default instance in http://wiki.duktape.org/HowtoNativeConstructor.html) in the load callback cb_load_module. But duktape complains

TypeError: [object Object] not constructable

when I evaluate var MyObject = require("MyObject"), no matter if I

  • push undefined into the value stack and return 1,
  • or push nothing into the value stack and return 0.


via Sean

Address bar and Angular 2 Routing with express

Ok, so I'm building an angular app and I need some clarification.

I have an express backend and am using Angular 2. So when I type in a url that is an angular route but not an express route into the address bar, it 404s while using routerlink='data' works.

My understanding of this is to do something like router.get('*', function(req, res) { render('angularApp') }

Now, if I build an api on the backend, won't this make the API unreachable? If so, how do I get around this?



via QueSo

All React Router and hashHistory routes redirect to same component

I am trying to use React Router on my MERN stack app am having trouble since all routes are rendering the same component

Router(index.jsx):

import React from 'react'
import ReactDOM from 'react-dom'
import { Router, Route, IndexRoute, hashHistory } from 'react-router'
import Home from './components/home.jsx'
import App from './app.jsx'
import ContactsIndex from './components/contacts/contactsIndex.jsx'

if(typeof window !== 'undefined') {
    ReactDOM.render(
    <Router history={hashHistory}>
        <Route path='/' component={App}>
          <IndexRoute component={Home} />
          <Route path='contacts' component={ContactsIndex}/>
        </Route>
    </Router>, document.getElementById("root"));
}

App.jsx

import React from 'react'
import { Router, Route, Link } from 'react-router'
import Home from './components/home.jsx'

export default class App extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return(
      <div>
        <p>Text</p>
        {this.props.children}
      </div>
    )
  }
}

Entry from express into React:

app.set('views', __dirname + '/views');
app.engine('jsx', require('express-react-views').createEngine())
app.set('view engine', 'jsx')

app.get('*', (req,res) => {
  res.render('index.jsx')
})

No Matter what route I visit(even one that are not defined) the contents of App.jsx are rendered. It seems that I'm doing something incorrectly here which is making hashHistory not work. I'm using React-Router 2.6.1



via John

How to prevent Jade case when to transpile every case? PS: I'm using includes

I'm working on a very large project, using gulp, node, jade templates and bem notation. When trying to locally serve the app, I have one file causing it to take around 4 minutes to compile!! I noticed this file, if commented out, reduces the load time to 24 seconds!

The file in question (that I need to improve/refactor) has a case/when and includes lots of things. It seems that jade renders every include to javascript FIRST and then looks at what files we need or not based on the case... This is the file, is there a way to improve this? THANKS!!

// START sos-shopping-overlay/shopping-overlay

include ../../_bem

-var $prefix = 'sos-'

+bemto_scope({prefix: $prefix})
        +b.component
                .common-vertical-align
                        .common-vertical-align__content
                                +e.overlay
                                        +e.A.close(href="#", title="Close Overlay")

                                        case $sosType
                                                when 'dashboard'
                                                        include ../../components/ssc__shopping-step-container/shopping-step-container__dashboard
                                                when 'deals'
                                                        include ../../components/ssc__shopping-step-container/shopping-step-container__your-deal
                                                when 'deal-details'
                                                        include ../../components/ssc__shopping-step-container/shopping-step-container__deal-details
                                                when 'sections'
                                                        include ../../components/ssc__shopping-step-container/shopping-step-container__your-section
                                                when 'deck'
                                                        include ../../components/ssc__shopping-step-container/shopping-step-container__your-deck
                                                when 'rooms'
                                                        include ../../components/ssc__shopping-step-container/shopping-step-container__your-room
                                                when 'paymentPlan'
                                                        include ../../components/ssc__shopping-step-container/shopping-step-container__payment-plan
                                                when 'mb-landing'
                                                        include ../../components/ssc__shopping-step-container/shopping-step-container__mb-landing
                                                when 'mb-preselected-room'
                                                        include ../../components/ssc__shopping-step-container/shopping-step-container__mb-preselected-room
                                                when 'mb-room-type'
                                                        include ../../components/ssc__shopping-step-container/shopping-step-container__mb-room-type
                                                when 'mb-deal'
                                                        include ../../components/ssc__shopping-step-container/shopping-step-container__mb-deal
                                                when 'mb-section'
                                                        include ../../components/ssc__shopping-step-container/shopping-step-container__mb-section
                                                when 'mb-deck'
                                                        include ../../components/ssc__shopping-step-container/shopping-step-container__mb-deck
                                                when 'mb-room'
                                                        include ../../components/ssc__shopping-step-container/shopping-step-container__mb-room
                                                default
                                                        h1 No step found


via Juanma Guerrero

How to know if a child procces is finished?

I try to build a bash terminal via web with Node.js and socket.io, and I need know if a command is finished. Some command like 'cd someDirectory' don't emit a output and I don't know if it finished. How to know if a command if finished? If posible set a timeout for each command? I have the following code:

var shell = spawn('/bin/bash');
var stdin = shell.stdin;

shell.on('exit', function() {
  socket.disconnect();
});

shell.on('close',function(){
  console.log('Close');
});

shell['stdout'].setEncoding('ascii');
shell['stdout'].on('data', function(data) {
  socket.emit('stdout', data);
});

shell['stderr'].setEncoding('ascii');
shell['stderr'].on('data', function(data) {
  socket.emit('stderr', data);
});

socket.on('stdin', function(command) {
  stdin.write(command+"\n") || socket.emit('disable');
});

stdin.on('drain', function() {
   socket.emit('enable');
});

stdin.on('error', function(exception) {
  socket.emit('error', String(exception));
});

Thanks in advance.



via Francisco Martin

Stripping HTML Down To Allowed Tags

I'd like to strip all HTML tags (but not the content), apart from ones given in a list.

I'd like to do this using Node.

The following regex can match tags <[a|br].+?>|<\/[a]> but how can I then proceed to remove all tags except the ones matched?



via Lolums

No redirect on failed passport authentication

New to nodejs, liking it so far, trying to do some custom handling for passport authentication. The success redirect works fine, however upon an unsuccessful attempt i would like to not continue the post event.
What I'm trying to accomplish is fire an alert off that opens a dialog (this part is working like I want, via the socket call) to the current page if there is an issue with the login attempt. The browser just waits if I don't call res.send() for example, or attempts to redirect to a page that does not exist if I do.

routes.js

app.post('/login', function (req, res, next) {
    passport.authenticate('local-login', function (err, user, msg) {
        if (err) {
            io.emit('status alert', err);
        }
        if (!user) {
            io.emit('status alert', msg);
            //res.send();
        }
        req.logIn(user, function (err) {
            if (err) {
                io.emit('status alert', err);
            }
            if (user) {
                return res.redirect('/loginsplash');
            }
        });
    })(req, res, next);
});

passport.js

passport.use(
    'local-login',
    new LocalStrategy({
        usernameField : 'username',
        passwordField : 'password',
        passReqToCallback : true
    },
    function (req, username, password, done) {
        db.getConnection().query("SELECT * FROM users WHERE uname = ?", [username], function (err, rows) {
            if (err)
                return done(err);
            if (!rows.length) {
                return done(null, false,  'Invalid Username or Password.');
            }

            // if the user is found but the password is wrong
            if (!bcrypt.compareSync(password, rows[0].upw))
                return done(null, false, 'Invalid Username or Password.');

            // all is well, return successful user
            return done(null, rows[0]);
        });
    })
);



via Vamp4L

In the browser showing empty while fetching data from mongodb and send to my getdata.ejs file

My index.js file get method

app.get('/getdata', function(req, res){
  var resultArray = [];
  mongo.connect(url, function(err, db){
    assert.equal(null, err);
    var cursor = db.collection('satyamsoft').find();
    cursor.forEach(function(doc, err){
      assert.equal(null, err);
      resultArray.push(doc);
      console.log(resultArray);
    });

  });

  res.render('pages/getdata', {holedata: resultArray});
});

My getdata.ejs file

<h2> Family Details </h2>
<ul>
    <% holedata.forEach(function(data) { %>
        <li><<%= data.name %> - <%= data.title %> - <%= data.age %></li>
    <% }); %>
</ul>

After executing the get method in the console showing data which is fetch from mongodbColnose data

But in the web page showing empty enter image description here

Am i doing anything wrong. Please help me. Advance thanks.



via Satyam

Add image to mongodb with mongoose

i am new to the MEAN steak and i am tryingto upload a file from my computer to my project and in the mongoDb databse. I don't need to use gridFs from mongo because my images are much smaller. Can someone give me an example, or tell me what's the logic.

Tannk you, Adrian



via Adrian

connecting angular web app to firebase

I watn to connect my web application to firebase,and I have VPN but after running, my dashboard component is not displayed and there are some errors :

An error occurred :Response app/hero.service.js:57 ERROR Error:node_modules/@angular/core/bundles/core.umd.js:1091 Uncaught (in promise): Response with status: 404 Not Found for URL: https://my firebase database name /.json

This is my code: DashboardComponent:

        import { Component, OnInit } from '@angular/core';
import {Http} from '@angular/http';
import { Hero }        from './hero';
import { HeroService } from './hero.service';


@Component({
  selector: 'my-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: [ './dashboard.component.css' ]
})
export class DashboardComponent implements OnInit {
  heroes: Hero[] = [];

  constructor(private heroService: HeroService) { }

  ngOnInit(): void {
    this.heroService.getHeroes()
      .then(heroes => this.heroes = heroes.slice(1, 5));

  }



}

hero.service.ts

          import { Injectable }    from '@angular/core';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { Hero } from './hero';

@Injectable()
export class HeroService {

  private headers = new Headers({'Content-Type': 'application/json'});
  private heroesUrl = "https://my firebase database name/.json";  // URL to web api

  constructor(private http: Http) { }

  getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }


  getHero(id: number): Promise<Hero> {
    const url = `${this.heroesUrl}/${id}`;
    return this.http.get(url)
      .toPromise()
      .then(response => response.json().data as Hero)
      .catch(this.handleError);
  }

  delete(id: number): Promise<void> {
    const url = `${this.heroesUrl}/${id}`;
    return this.http.delete(url, {headers: this.headers})
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  create(name: string): Promise<Hero> {
    return this.http
      .post(this.heroesUrl, JSON.stringify({name: name}), {headers: this.headers})
      .toPromise()
      .then(res => res.json().data as Hero)
      .catch(this.handleError);
  }

  update(hero: Hero): Promise<Hero> {
    const url = `${this.heroesUrl}/${hero.id}`;
    return this.http
      .put(url, JSON.stringify(hero), {headers: this.headers})
      .toPromise()
      .then(() => hero)
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
}

index.html

  <!DOCTYPE html>
    <html>
  <head>
    <base href="/">
    <title>Angular Tour of Heroes</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="styles.css">

    <!-- Polyfills -->
    <script src="node_modules/core-js/client/shim.min.js"></script>

    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
      System.import('main.js').catch(function(err){ console.error(err); });
    </script>


  <body>
    <my-app>Loading...</my-app>
    <script src="https://www.gstatic.com/firebasejs/3.9.0/firebase.js"></script>
    <script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js"></script>

<script>
  // Initialize Firebase
  var config = {
    apiKey: "my firebase project apikey",
    authDomain: "my firebase projec domain name",
    databaseURL: "my firebase projec database name",
    projectId: "my firebase projec ID",
    storageBucket: "my firebase projec storage",
    messagingSenderId: "my firebase projec senderId"
  };
  firebase.initializeApp(config);
</script>


  </head>
  </body>
</html>

app.module.ts

     import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { HttpModule }    from '@angular/http';

import { AppRoutingModule } from './app-routing.module';

// Imports for loading & configuring the in-memory web api
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService }  from './in-memory-data.service';

import { AppComponent }         from './app.component';
import { DashboardComponent }   from './dashboard.component';
import { HeroesComponent }      from './heroes.component';
import { HeroDetailComponent }  from './hero-detail.component';
import { HeroService }          from './hero.service';
import { HeroSearchComponent }  from './hero-search.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    InMemoryWebApiModule.forRoot(InMemoryDataService),
    AppRoutingModule
  ],
  declarations: [
    AppComponent,
    DashboardComponent,
    HeroDetailComponent,
    HeroesComponent,
    HeroSearchComponent
  ],
  providers: [ HeroService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }



via Gandom

Node Package Manager Failing on Browserify Script

There are lots of moving parts for this question so I will post everything. I am running npm run build and I get the following:

enter image description here

Here is my build script in package.json file:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build":"browserify -d app/scripts/src/main.js -o app/scripts/dist/main.js" 
  },
  "browserify":{
    "transform":[
      "babelify",{"presets":["es2015"],"sourceMap":true}
    ]
  },

app.js:

class ChatApp {
  constructor() {
    console.log("Hello World")
  }
}
 export default ChatApp 

main.js:

import ChatApp from './app'
new ChatApp()

Node version: 6.9.4

Browserify version: 14.3.0



via john doe

SQL Error: ER_CONCOUNT_ERROR: Too many connection

I'm making a Discord Bot which is comprised of Discord.js which I have some SQL to store commands people make. After a while of leaving the bot on I get this error Error: ER_CON_COUNT_ERROR: Too mant connections and it crashes the bot. This is the full error:

C:\Users\Jake\Desktop\MyBot\app.js:112
  if (error) throw error;
           ^

Error: ER_CON_COUNT_ERROR: Too many connections
  at Handshake.Sequence._packetToError (C:\Users\Jake\Desktop\MyBot\node_modules\mysql\lib\protocol\sequences\Sequence.js:52:14)
  at Handshake.ErrorPacket (C:\Users\Jake\Desktop\MyBot\node_modules\mysql\lib\protocol\sequences\Handshake.js:103:18)
  at Protocol._parsePacket (C:\Users\Jake\Desktop\MyBot\node_modules\mysql\lib\protocol\Protocol.js:280:23)
  at Parser.write (C:\Users\Jake\Desktop\MyBot\node_modules\mysql\lib\protocol\Parser.js:75:12)
  at Protocol.write (C:\Users\Jake\Desktop\MyBot\node_modules\mysql\lib\protocol\Protocol.js:39:16)
  at Socket.<anonymous> (C:\Users\Jake\Desktop\MyBot\node_modules\mysql\lib\Connection.js:103:28)
  at emitOne (events.js:96:13)
  at Socket.emit (events.js:191:7)
  at readableAddChunk (_stream_readable.js:178:18)
  at Socket.Readable.push (_stream_readable.js:136:10)
--------------------
  at Protocol._enqueue (C:\Users\Jake\Desktop\MyBot\node_modules\mysql\lib\protocol\Protocol.js:141:48)
  at Protocol.handshake (C:\Users\Jake\Desktop\MyBot\node_modules\mysql\lib\protocol\Protocol.js:52:41)
  at Connection.connect (C:\Users\Jake\Desktop\MyBot\node_modules\mysql\lib\Connection.js:130:18)
  at Client.client.on (C:\Users\Jake\Desktop\MyBot\app.js:100:14)
  at emitOne (events.js:101:20)
  at Client.emit (events.js:191:7)
  at MessageCreateHandler.handle (C:\Users\Jake\Desktop\MyBot\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
  at WebSocketPacketManager.handle (C:\Users\Jake\Desktop\MyBot\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:120:65)
  at WebSocketManager.eventMessage (C:\Users\Jake\Desktop\MyBot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:273:31)
  at WebSocket.onMessage (C:\Users\Jake\Desktop\MyBot\node_modules\ws\lib\WebSocket.js:442:14)

I'm not sure on what this means but the code around the error which throw this is:

  connection.query("SELECT * FROM commands WHERE guildid = '" + message.guild.id + "'", info, function(error, theCommands) {
    if (error) throw error;

    if (theCommands.length) {
      theCommands.forEach(eachCommand => {
        if (message.content == eachCommand.commandname) return message.channel.sendMessage(eachCommand.commandreply);
      });
    };
  });



via Rusty

Agar.io with sockets

i'm doing an agar.io game on javascrip, html, sockets and node.js game. I want my game to show me the same contenent on all localhost pages but it's does'nt work. please Help Me. Here is my code



via Sifo Hireche

Json Schema: Validating Arrays

I'm trying to validate a schema that includes two keys, tags and parameters, which are intended to be arrays of arbitrary key-value pairs. For some reason, though, I can't get anything I specify for these two keys to fail validation (I'm using the nodejs library ajv).

Here is the schema definition:

{
  name: { type: "string" },
  application: { type: "string" },
  account: { type: "string" },
  environment: { type: "string" },
  tags: { 
    type: "array",
    items: {
      type: "object",
      patternProperties: {
        "^[a-zA-z0-9]$": { type: "string" }
      },
      additionalProperties: false
    },
    additionalItems: false
  },
  parameters: { 
    type: "array",
    items: {
      type: "object",
      patternProperties: {
        "^[a-zA-z0-9]$": { type: "string" }
      },
      additionalProperties: false
    },
    additionalItems: false
  },
  deps: { type: "array", items: { type: "string" } },
  required: ["name", "account", "environment", "parameters", "application"]
}

And here is a test object. I'm passing parameters here as a simple string, intending it to fail validation, but it actually passes:

{ name: "test", 
            account: "test", 
            environment: "test",
            parameters: "test",
            application: "test"
          }

Please tell me what I'm doing wrong. Thanks.



via rumdrums

"npm run dev" not working on Windows

Laravel Version: 5.4.21

PHP Version: 7.1.1

node v4.4.5

npm v4.5.0

npm commands are completely broken on windows (windows 7 in this case), whenever I run npm run dev I get the following error:

> @ dev E:\xampp\htdocs\laravelblog
> npm run development


> @ development E:\xampp\htdocs\laravelblog
> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

E:\xampp\htdocs\laravelblog\node_modules\laravel-mix\setup\webpack.config.js:1
(function (exports, require, module, __filename, __dirname) { let path = require('path');
                                                              ^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at requireConfig (E:\xampp\htdocs\laravelblog\node_modules\webpack\bin\convert-argv.js:96:18)
    at E:\xampp\htdocs\laravelblog\node_modules\webpack\bin\convert-argv.js:109:17
    at Array.forEach (native)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ development script 'cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the  package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls
npm ERR! There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\winuser-pc\AppData\Roaming\npm-cache\_logs\2017-04-29T18_27_27_864Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ dev script 'npm run development'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the  package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm run development
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls
npm ERR! There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\winuser-pc\AppData\Roaming\npm-cache\_logs\2017-04-29T18_27_27_938Z-debug.log

I tried default package.json

{
  "private": true,
  "scripts": {
    "dev": "npm run development",
    "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch-poll": "npm run watch -- --watch-poll",
    "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "prod": "npm run production",
    "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
  },
  "devDependencies": {
    "axios": "^0.15.3",
    "bootstrap-sass": "^3.3.7",
    "cross-env": "^3.2.3",
    "jquery": "^3.1.1",
    "laravel-mix": "0.*",
    "lodash": "^4.17.4",
    "vue": "^2.1.10"
  }
}

I also tried other helps from internet as well like this one

"scripts": {
    "dev": "node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "hot": "node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "production": "node node_modules/cross-env/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
  },

Guide me what's wrong here. Why it is not working



via Soli

Parse Dashboard is blank

I've set up of Parse-Server with mongodb on same instance, in amazon, EC2.

I can't get acess to parse-dashboard because I didn't install SSL certificate, so I used nginx + Let's Encrypt to solve this.

But now when I try to acess parse-server I get:

Cannot Get login

How to solve this ? Here is my dashboard config:

{
  "apps": [
    {
        "serverURL": "http://mysvrurl/parse", 
        "appId": "myappid",
        "masterKey": "mykey",
        "appName": "appname"
    }
  ],
  "users": [
    {
      "user":"user", 
      "pass":"p@ssw0rd"
    }



via lipesmile

How to setup node with webpack dev server?

I want to proxy all /bundle urls to webpack dev server.

I have followed the advice from this question which does the same thing.

However, I still can't see my publicFiles served from localhost:8081/bundle? The silly thing is I have another project not based on react which works just fine, but this just says:

Cannot GET /bundle/

when accessing localhost:8081/bundle .

If you can point out what I'm missing I would really appreciate it. It must be something silly since I know this has to work.

Working in development mode

Here is my webpack config

'use strict';
var webpack = require('webpack');
const autoprefixer = require('autoprefixer');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CompressionPlugin = require('compression-webpack-plugin');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
let getPlugins;
var isProd = (process.env.NODE_ENV === 'production');
console.log("Production: " + isProd);

let entryFill = null;
let publicPathFill = null;
if (isProd) {
    entryFill = {
        bootstrap: ['bootstrap/dist/css/bootstrap.css', 'bootstrap/dist/js/bootstrap.js'],
        index: ['./src/bundle/index.tsx'],
        vendor: ['react', 'react-dom', 'jquery', 'jquery-ui-bundle', "redux-thunk", 'redux', 'react-redux']
    }

    publicPathFill = "./dist/assets/bundle";
    getPlugins = function () {
        return [
            new SWPrecacheWebpackPlugin(
                {
                    cacheId: 'cleaning-website',
                    filename: 'service-worker.js',
                    maximumFileSizeToCacheInBytes: 4194304,
                    runtimeCaching: [{
                        handler: 'cacheFirst',
                        urlPattern: /[.]js$/
                    }],
                }
            ),
            new ExtractTextPlugin("site.css"),
            new webpack.optimize.UglifyJsPlugin(),
            new webpack.optimize.OccurrenceOrderPlugin(),
            //new webpack.optimize.DedupePlugin(),
            //new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
            //new webpack.optimize.AggressiveMergingPlugin(),
            new webpack.ProvidePlugin({
                jQuery: 'jquery',
                $: 'jquery',
                jquery: 'jquery'
            })
            //new CompressionPlugin({
            //    asset: "[path].gz[query]",
            //    algorithm: "gzip",
            //    test: /\.js$|\.css$|\.tsx$/,
            //    threshold: 10240,
            //    minRatio: 0.8
            //})
        ]
    }
} else {
    entryFill = {
        bootstrap: ['bootstrap/dist/css/bootstrap.css', 'bootstrap/dist/js/bootstrap.js', 'webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:8081'],
        index: ['./src/bundle/index.tsx', 'webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:8081'],
        vendor: ['react', 'react-dom', 'jquery', 'jquery-ui-bundle', "redux-thunk", 'redux', 'react-redux', 'webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:8081']
    }

    publicPathFill =  "http://localhost:8081/bundle/",
    //publicPathFill = "/",

    getPlugins = function () {
        return [
            new ExtractTextPlugin("site.css"),
            new webpack.HotModuleReplacementPlugin()
        ]
    }

}

module.exports = {
    /**
     * Entry for all client side code.
     * @var {object} entry
     */
    entry: entryFill,
    plugins: getPlugins(),

    output: {
        path: publicPathFill,
        filename: '[name].js',
        libraryTarget: 'umd'
        publicPath: 'http://localhost:8081/bundle/'
    },
    resolve: {
        extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"],
        //alias: {
        //    'react': 'preact-compat',
        //    'react-dom': 'preact-compat',
        //    'react-router': 'preact-compat'
        //}

    },
    module: {
        loaders: [
            //  { test: /\.(jpe?g|png|gif|svg)$/i, loader: 'url?limit=10000!img?progressive=true'},
            { test: /\.css$/, loader: "style-loader!css-loader" },
            {
                test: /\.scss$/,
                loader: ExtractTextPlugin.extract(
                    //Need:?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5] to set the right name for each css!
                    "style",
                    "css!postcss-loader!sass")
            },
            //  { test: /bootstrap-sass\/assets\/javascripts\//, loader: 'imports?jQuery=jquery' },
            { test: /\.tsx?$/, loader: "ts-loader" },
            {
                test: /\.(pug|png|ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
                loader: 'file-loader'
            }
        ]
    },
    postcss: function () {
        return [autoprefixer(
            //    { browsers: ['ie 10', 'firefox 20', 'safari 9.1','Chrome ] }
            { browsers: ['> 0%'] }
        )];
    }
};

and my webpack dev server running in node looks like:

import * as express from 'express';
import * as path from 'path'

let webpack = require('webpack');
let WebpackDevServer = require('webpack-dev-server');
let proxy = require('proxy-middleware');
let url = require('url');
let config = require('../../../webpack.config.js');

import { post } from "./post";
import { pages } from "./pages";
module.exports = function (app: any, passport: any) {
    var router = express.Router();
    post(router, passport);
    pages(router);
    if (process.env.NODE_ENV === 'development') {
        let base = path.join(__dirname, "..", "..", "assets");
        console.log("Base : " + base);
        //console.log(__dirname);
        let server = new WebpackDevServer(webpack(config), {
            //contentBase: base,
            hot: true,
            quiet: false,
            noInfo: false,
            publicPath: "/bundle/",

            stats: { colors: true }
        });
        server.listen(8081, "localhost", function () { });
        app.use('/bundle', proxy(url.parse('http://localhost:8081/bundle')));
    }
    app.use('/', router);
};

I serve the html page like so:

import { createStore, bindActionCreators, applyMiddleware } from 'redux';
import { routerReducer } from 'react-router-redux'
import  thunkMiddleware  from 'redux-thunk'
import * as path from 'path'
import * as fs from "fs";
import { Routes, Navigation, RootReducer } from "../../client/index";

export function pages(router) {

    router.get('/*', function (req: any, res: any, next) {
        let initial = {};
        const store = createStore(RootReducer, initial, applyMiddleware(thunkMiddleware))
        const body = ReactDOMServer.renderToString(
            <Provider store={store}>
                <StaticRouter location={req.url}>
                    <Routes/>
                </StaticRouter>
            </Provider>
        )
        //const nav = ReactDOMServer.renderToString(
        //    <Navigation/>
        //)
        const nav = ReactDOMServer.renderToString(
            <div> Nav</div>
        )
        console.log("Body:");
        console.log(body);
        //const state = store.getState()
        const state = {};
        res.send(`
                <!DOCTYPE html>
                <html lang="en">
                <head>
                  <meta charset="UTF-8">
                  <meta name="viewport" content="width=device-width, initial-scale=1">
                  <title>Clement Cleaning</title>
                  <meta name="description" content="A cleaning business">
                  <meta name="author" content="Mortonproductions">
                  <script src="/bundle/bootstrap.js"></script>
                  <link rel="stylesheet" href="/bundle/site.css">
                </head>
                <body>
                  <header>
                    <h1>
                        Clement Cleaning
                    </h1>
                    <h2>
                        A cleaning business based in Loch Lomond
                    </h2>
                  </header>
                  <nav>
                    <div id="react-nav">${nav}</div>
                  </nav>
                  <section>
                    <div id="react-router">${body}</div>
                  </section>
                  <footer>
                     Progressive web app produced my morton productions 
                  </footer>
                  <script>window.__REDUX_STATE__ = ${JSON.stringify(state)}</script>
                  <script src="/bundle/vendor.bundle.js"></script>
                  <script src="/bundle/index.js"></script>
                </body>
                </html>`
        )
    });
}



via mortonprod

Module not found: Error: Can't resolve 'Peerjs'

I'm trying to use Peerjs with React.

At the top of my component i have

import Peer from 'Peerjs'

which I installed with npm. Code works fine on my local nodejs server but when i upload it on aws instance i have this notification:

Module not found: Error: Can't resolve 'Peerjs' in '/var/www/vhost/src/lib'

I even do not guess what it might be?



via Eugeniy Gromov