Saturday 27 May 2017

Where is semver coming from?

I keep getting semver Duplicate resources error, even though semver is neither any of of node modules I defines nor any of theri tertiary dependency. Keeping aside the reson of Duplicate resources I am more curious how is it coming in the first place.

Could not merge source set folders: [app/node_modules/semver/semver.min.js] /Users/ishandutta2007/Documents/Projects/bb-ns-ng-dr/platforms/android/src/main/assets/app/node_modules/semver/semver.min.js [app/node_modules/semver/semver.min.js] /Users/ishandutta2007/Documents/Projects/bb-ns-ng-dr/platforms/android/src/main/assets/app/node_modules/semver/semver.min.js.gz: Error: Duplicate resources [app/node_modules/semver/semver.browser.js] /Users/ishandutta2007/Documents/Projects/bb-ns-ng-dr/platforms/android/src/main/assets/app/node_modules/semver/semver.browser.js [app/node_modules/semver/semver.browser.js] /Users/ishandutta2007/Documents/Projects/bb-ns-ng-dr/platforms/android/src/main/assets/app/node_modules/semver/semver.browser.js.gz: Error: Duplicate resources

Here is how my node modules package tree looks like

MacBook-Pro:bb-ns-ng-dr ishandutta2007$ npm ls
/Users/ishandutta2007/Documents/Projects/bb-ns-ng-dr
├── @angular/animations@4.1.3
├── @angular/common@4.1.3
├── @angular/compiler@4.1.3
├── UNMET PEER DEPENDENCY @angular/core@4.1.3
├── @angular/forms@4.1.3
├── @angular/http@4.1.3
├── @angular/platform-browser@4.1.3
├── @angular/platform-browser-dynamic@4.1.3
├── @angular/router@4.1.3
├── @ngrx/core@1.2.0
├── @ngrx/effects@2.0.2
├── @ngrx/store@2.2.1
├── @ngrx/store-devtools@3.2.4
├── @types/gapi@0.0.30
├── @types/gapi.auth2@0.0.34
├── @types/gapi.youtube@3.0.31
├── @types/jasmine@2.5.38
├── @types/youtube@0.0.28
├─┬ babel-traverse@6.24.1
│ ├─┬ babel-code-frame@6.22.0
│ │ ├─┬ chalk@1.1.3
│ │ │ ├── ansi-styles@2.2.1
│ │ │ ├── escape-string-regexp@1.0.5
│ │ │ ├─┬ has-ansi@2.0.0
│ │ │ │ └── ansi-regex@2.1.1
│ │ │ ├── strip-ansi@3.0.1
│ │ │ └── supports-color@2.0.0
│ │ └── js-tokens@3.0.1
│ ├── babel-messages@6.23.0
│ ├─┬ babel-runtime@6.23.0
│ │ ├── core-js@2.4.1
│ │ └── regenerator-runtime@0.10.5
│ ├─┬ debug@2.6.8
│ │ └── ms@2.0.0
│ ├── globals@9.17.0
│ ├─┬ invariant@2.2.2
│ │ └── loose-envify@1.3.1
│ └── lodash@4.17.4
├─┬ babel-types@6.24.1
│ ├── esutils@2.0.2
│ └── to-fast-properties@1.0.3
├── babylon@6.17.1
├── lazy@1.0.11
├─┬ nativescript-angular@3.0.0
│ └── nativescript-intl@3.0.0
├─┬ nativescript-dev-typescript@0.4.5
│ └─┬ nativescript-hook@0.2.1
│   ├─┬ glob@6.0.4
│   │ ├─┬ inflight@1.0.6
│   │ │ └── wrappy@1.0.2
│   │ ├── inherits@2.0.3
│   │ ├─┬ minimatch@3.0.4
│   │ │ └─┬ brace-expansion@1.1.7
│   │ │   ├── balanced-match@0.4.2
│   │ │   └── concat-map@0.0.1
│   │ ├── once@1.4.0
│   │ └── path-is-absolute@1.0.1
│   └─┬ mkdirp@0.5.1
│     └── minimist@0.0.8
├── nativescript-exoplayer@3.0.7
├── nativescript-localstorage@1.1.2
├── nativescript-telerik-ui@2.0.1
├── nativescript-theme-core@1.0.4
├── ngrx-action-creator-factory@0.0.1
├── ngrx-store-localstorage@0.1.5
├── reflect-metadata@0.1.10
├─┬ rxjs@5.3.3
│ └── symbol-observable@1.0.4
├─┬ tns-core-modules@3.0.1
│ └── tns-core-modules-widgets@3.0.1
├── typescript@2.2.2
└── zone.js@0.8.11

npm ERR! peer dep missing: @angular/core@^2.0.0, required by @ngrx/effects@2.0.2
npm ERR! peer dep missing: @angular/core@^2.0.0, required by @ngrx/store@2.2.1
npm ERR! peer dep missing: @angular/core@^2.0.0-rc.5, required by ngrx-store-localstorage@0.1.5

PS: I also did the following before building:

npm uninstall -g semver
MacBook-Pro:bb-ns-ng-dr ishandutta2007$ npm uninstall  semver
MacBook-Pro:bb-ns-ng-dr ishandutta2007$ rm -rf platforms/
MacBook-Pro:bb-ns-ng-dr ishandutta2007$ rm -rf node_modules/



via ishandutta2007

Error in Mongoose Installation

While installing mongoose, I am facing this error. I have also increase the space but still not fixed the problem.

Error -

This is the error



via gokha

How can I import semantic-ui css and js in vue component?

I wanted to import semantic-ui just like the code below, but seems like It doesn't work and I'm not sure how to fix it. I downloaded semantic-ui like npm i semantic-ui. and I have no idea how to import it. need help!

<style>
import url('semantic-ui.css')
</style>

<script>
import 'semantic-ui'
</script>



via Phillip YS

Node JS goole oauth2 using access_token after expirition date

Here the story:

I'm developing iOS application, connected to Node JS server. I'm asking the user to authenticate and give me permissions to read and edit his google calendar. After the authentication is done, I'm getting auth_token, refresh_token and the expiry_date. I'm storing them, because my server app, has to do some API calls in the future (after the expiry date). On the server side I'm building oauth2Client object:

var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
oauth2Client.credentials = {access_token:tokenData.accessToken, 
refresh_token:tokenData.refreshToken,
expiry_date:tokenData.expirationDate,token_type:'Bearer'};

var calendar = google.calendar('v3');
calendar.events.list({
    auth: auth,
    calendarId: calendarId,
    timeMin: dateFrom.toISOString(),
    timeMax:dateTo.toISOString(),
    singleEvents: true,
    orderBy: 'startTime'
}, function(err, response) {

});

It all works perfectly fine untiil the token expires. My question is: Can I refresh the token from my server without asking the user? Or what is the best practice in that case?

I tried:

oauth2Client.refreshAccessToken(function(err, tokens) {        
});

but it gives me unauthorized_client error



via gpopov

Auto update template string value without refreshing the page

So, when I refresh the page, the template string is updated to it's new value which is pulled from the database and is ever so changing.

Is there a way that I can use ajax or something similar to auto refresh the value of the template string?

This is the template string here:

enter image description here

It's being pulled from a GET request which performs a database lookup of the value.



via kolbykskk

Nodejs: s3 getObject for very large number of files download and archive fails

I am able to download very large ~2000 files from s3 bucket to local disk in python using boto.s3.resumable_download_handler and boto.s3.connection. download and archive to tar file in local disk. It works.

I am trying the same functionality in nodejs: If I am trying to download below ~500 files using s3 getObject and archive . Files gets downloaded and archived to local disk (using nodejs).

I am trying to download very large ~2000 files using s3 getObject and archive these files from the server to local disk using archive in nodejs. I am getting s3 error: Please reduce your request rate.ServiceUnavailable: Please reduce your request rate.

   Code Snippet:
        var AWS = require('aws-sdk');
        var archiver = require('archiver');
        var fs = require('fs');
        var OutputFileName = 'abc.zip'

         s3Client.listObjects(parameters, function(error, data) {
var dataConts = data.Contents;
dataConts.forEach(function(dataE) {
    var aparams = {Bucket: bucketName, Key: dataE.Key};

                    archive.append(s3Client.getObject(aparams).createReadStream(),
                                            {name: dataE.Key});

           //archive on error
            archive.on('error', function(error) {
                throw error;
            });
            //archive on end of processing
            archive.on('end', function() {

                callback();
            });
            response.attachment(OutputFileName);

           archive.pipe(respose);
           archive.finalize();

can anyone let me know whether s3 and archive can be used in any other way to download and archive the very large number of files.



via Yamini

Node MySQL Left join the multiple rows into one

Currently, I'm using Node MySQL library to implement MySQL query in Javascript framework. I have an issue about the left join with multiple rows. When I left join that table, it returns more than one object, this is because the left join will produce duplicate rows but different values of that particular attribute. What I want to achieve right now is, returns one object and insert that multiple values to array of that particular attribute.

Table A

id | name | age
 1   abel   22
 2   john   22

Table B

id | user_id | equip
 1      1      armor
 2      2      sword
 3      1      knife

Query

SELECT * FROM Table_A LEFT JOIN TABLE_B ON TABLE_B.user_id = TABLE_A.id;

Current Situation

{
    id: 1
    name: abel
    age: 22
    user_id: 1
    equip: 'armor'
},
{
    id: 1
    name: abel
    age: 22
    user_id: 1
    equip: 'knife'
}

What I want to achieve

{
    id: 1
    name: abel
    age: 22
    user_id: 1
    equip: [
       'armor','knife'
    ]
}



via Abel Chun

Multipart Form Data not Sending Correctly

I have been unable to make this work...

The Tools

  • HTML5
  • CSS
  • Bootstrap 3.x.x
  • NodeJS (Express, multer)
  • jQuery

The Problem

It Appears that the post is being logged but the req.files is not being populated and no images are being pushed into my uploads folder.

The JS

$(document).ready(function () {
    var form = $('#ajax-new-post');

    form.submit(function (e) {

        //stop submit the form, we will post it manually.
        e.preventDefault();

        var formMessages = $('#form-messages');

        // Create an FormData object
        var data = new FormData(form[0]);

        // If you want to add an extra field for the FormData
        //data.append("CustomField", "This is some extra data, testing");

        // disabled the submit button
        $("#btnSubmit").prop("disabled", true);

        $.ajax({
            type: "POST",
            enctype: 'multipart/form-data',
            url: "/posts/new",
            data: data,
            processData: false,
            contentType: false,
            cache: false,
            timeout: 600000,
            })
                .done(function (response) {
                    // Make sure that the formMessages div has the 'success' class.
                    $(formMessages).removeClass('alert alert-danger');
                    $(formMessages).addClass('alert alert-success');

                    console.log('Success: ' + response);

                    // Set the message text.
                    $(formMessages).text(response);

                    // Clear the form.
                    $('#title').val('');
                    $('#image').val('');
                    $('#upload-file-info').removeClass('btn-blk');
                    $('#upload-file-info').val('');
                    $('#post').val('');
                    $('#category').val('');
                })
                .fail(function (data) {
                    // Make sure that the formMessages div has the 'error' class.
                    $(formMessages).removeClass('alert alert-success');
                    $(formMessages).addClass('alert alert-danger');

                    // Set the message text.
                    if (data.responseText !== '') {
                        $(formMessages).text(data.responseText);
                    } else {
                        $(formMessages).text('Oops! An error occured and your message could not be sent.');
                    }
                });
        });

});

The HTML

<div id="form-messages"></div>
<form id="ajax-new-post" enctype="multipart/form-data" method="post" action="/posts/new" class="wpcf7-form">

    <!--<label for="name">Name:</label>-->
    <div class="field">
        <input type="text" id="title" name="title" placeholder="Title" required>
    </div>
    <div class="e-divider-2"></div>
    <div class="row">
        <div class="col-md-6">
            <input type="text" id="category" class="text-align-left" name="category" placeholder="Category" style="float: left;" required>
        </div>
        <div class="col-md-6">
            <input type="file" id="image" name="image" accept="image/*" size=1>
        </div>
    </div>
    <div class="e-divider-1"></div>
    <div class="field">
        <!--<label for="message">Message:</label>-->
        <textarea id="content-mrkdwn" name="content_mrkdwn" placeholder="Post" rows="40" required></textarea>
    </div>
    <div class="e-divider-2"></div>
    <div class="field text-center">
        <button id="btnSubmit" type="submit" class="btn btn-lg btn-blk">Create Post</button>
    </div>
</form>

The Server Side

let uploading = multer({
    dest: __dirname + /public/uploads/images/'
}).single('image');

app.post('/posts/new', uploading, (req, res) => {
    console.log(req.body);  // Outputting Non-Multipart Data
    console.log(req.files); // Outputting Undefined

    res.status(202).send('Post Successfully Made');
});

Any Thoughts???



via canaan seaton

MongoDb Atlas failed to connect to server [123:27017] on first connect

I'm trying to connect to a MongoDB in MongoDB Atlas, but I'm receing this error:

{ MongoError: failed to connect to server [123:27017] on first connect [MongoError: connect EHOSTUNREACH 0.0.0.123:27017 - Local (192.168.15.6:56553)]
    at Pool.<anonymous> (/Users/filipeferminiano/node_modules/mongodb-core/lib/topologies/server.js:328:35)
    at emitOne (events.js:96:13)
    at Pool.emit (events.js:191:7)
    at Connection.<anonymous> (/Users/filipeferminiano/node_modules/mongodb-core/lib/connection/pool.js:280:12)
    at Object.onceWrapper (events.js:293:19)
    at emitTwo (events.js:106:13)
    at Connection.emit (events.js:194:7)
    at TLSSocket.<anonymous> (/Users/filipeferminiano/node_modules/mongodb-core/lib/connection/connection.js:177:49)
    at Object.onceWrapper (events.js:293:19)
    at emitOne (events.js:96:13)
  name: 'MongoError',

This is my code:

var db;
var mongoServer = 'mongodb://[USER]:[PASSWORD]@roas-shard-00-00-r4v7u.mongodb.net:27017,roas-shard-00-01-r4v7u.mongodb.net:27017,roas-shard-00-02-r4v7u.mongodb.net:27017/[DATABASE]?ssl=true&replicaSet=roas-shard-0&authSource=admin'.replace(/\\/g, "\\\\");

MongoClient.connect(mongoServer, (err, database) => {
   if (err) return console.log(err)
      db = database
      app.listen(3000, () => {
        console.log('listening on 3000')
  })
})



via Filipe Ferminiano

Use an encrypted file as your database instead of mongodb for your node/express app

How can I use an encrypted file as your database instead of MongoDB or MySQL for your node/express app

where you will give your DB will be of a JSON format and there will be a service that backs it up at regular interval.

It could look like this

{
  "info": {
    "version": "0.0.1",
    "name": "Give your DB a name"
  },
  "data": {

  }
}

and have methods like

myDB.info() // => {"version" : "0.0.2", "name": "demo DB"}

myDB.get('foo'); // => 'bar'

myDB.set('foo', 'bar');

myDB.delete(key);

myDB.backup(function(err) {
    if(err) throw err;
    else console.log('DB backed up at %s', new Date().toString());
});

myDB.search('stats.comments_lookup[{stats.page.id}]', function(res) {
    console.log("search result: ", res);
});

I saw this npm package called express-db but it's outdated and not maintained. Any better option or way of doing this?



via Jalasem

Adaptive Cards render on skype and emulator, but not web chat

I have a added a few Adaptive Cards to my bot. They render perfectly in the emulator and, when deployed, render perfectly in Skype and Slack. However, in the web chat, I get the following response instead of the rendered card:

[File of type 'application/vnd.microsoft.card.adaptive']

Any thoughts on what the problem might be? I'm uncertain how to troubleshoot when the functionality works in all the other environments.

I'm use the Node version of the bot framework.



via HardlyNeutral

Knex js using incorrect database within AWS Elastic Beanstalk

I have uploaded a node app to aws elastic beanstalk and it has worked perfectly, apart from it using the wrong Knex database.

My knex file looks like this

module.exports = {
    production: {
        client: 'mysql',
        connection: {
            host: process.env.RDS_HOSTNAME,
            port: process.env.RDS_PORT,
            user: process.env.RDS_USERNAME,
            password: process.env.RDS_PASSWORD,
            database: process.env.RDS_DB_NAME,
        },
        pool: {
            min: 2,
            max: 10
        },
        migrations: {
            tableName: 'knex_migrations'
        }
    },
    development: {
        client: 'mysql',
        connection: {
            socketPath : '/Applications/MAMP/tmp/mysql/mysql.sock',
            user : 'root',
            password : 'root',
            database : 'testDb'
        },
        pool: {
            min: 2,
            max: 10
        },
        migrations: {
            tableName: 'knex_migrations'
        }
    }
};

I have set my NODE_ENV value to 'production' using the EB console, and returning 'process.env.NODE_ENV' confirms it to be 'production'.

However when I run a DB query, it errors with

error": {
    "code": "ENOENT",
    "errno": "ENOENT",
    "syscall": "connect",
    "address": "/Applications/MAMP/tmp/mysql/mysql.sock",
    "fatal": true
  }

Which shows it using the development database. I have returned all the variables for the RDS database and they are set by EB correctly. My 'npm start' is simply 'node dist/index.js'

Any ideas why its picking up the wrong database? If I hard code both of them to the production config, it uses it.



via drm18272

Realm is getting error : Error: Cannot find module 'realm' .

I am creating an app where I using Realm, and all of sudden I am getting this error when doing node index.js which I get Error: Cannot find module 'realm'

and when I do npm install I get this error: Could not install /**********/realm-professional.tgz

Here are the code.

    'use strict';

var fs = require('fs');
var Realm = require('realm');
var VisualRecognition = require('watson-developer-cloud/visual-recognition/v3');


var REALM_ADMIN_TOKEN = "***************";



var BLUEMIX_API_KEY = "***********";


var SERVER_URL = 'realm://127.0.0.1';


var NOTIFIER_PATH = ".*/*****"; 

The Json file

    {
  "name": "MyApp",
  "version": "0.0.1",
  "description": "Use Realm Object Server's event-handling.",
  "main": "index.js",
  "author": "Realm",
  "dependencies": {
    "realm": "file:realm-professional.tgz",
    "watson-developer-cloud": "^2.11.0"
  }
}



via Jośe

Changing password with passport local mongoose (MEAN Stack)

I am trying to setup a forgot password feature on my MEAN Stack app.

I managed to get the emails to send, the tokens to update and the password to change, but not exactly how I want it to.. I just changed my password to "daviddavid", and here's how it was stored in the database: "password" : "$2a$08$cUdbJP5V.0Af.H2r5bsiW.IqHvo7K2eQk/hQK72aHOHWDYkFs3KHm". So, the hash is being stored as the password, and not the password itself as hash and salt.

Here's my model:

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var bcrypt = require("bcrypt");

var userSchema = new mongoose.Schema({
    username: {type: String, minlength: 4, maxlength: 15},
    password: {type: String, minlength: 8},
    email: {type: String, unique: true, lowercase: true, required: true},
    admin: {type:Boolean, default: false},
    bio: {type:String, default: "Cet utilisateur n'a pas encore rempli cette section."},
    profileImage: {type:String, default: "http://www.wilwia.com/images/default-user.png"},
    pinnedRecipes:[
        {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Recipe"
        }
    ],
    resetPasswordToken: String,
    resetPasswordExpires: Date
});

userSchema.pre('save', function(next){
    var user = this;

    //check if password is modified, else no need to do anything
    if (!user.isModified('password')) {
       return next();
    }

    user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(8), null);
    next();
});

userSchema.plugin(passportLocalMongoose);

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

Here's my password reset route:

// FORGOT PASSWORD ROUTES

var options = {
  auth: {
    api_user: 'YelpCamp',
    api_key: '***'
  }
}
var mailer = nodemailer.createTransport(sgTransport(options));
/*Routes*/
router.post('/forgot', function(req, res, next) {
async.waterfall([
    function(done) {
      crypto.randomBytes(20, function(err, buf) {
        var token = buf.toString('hex');
        done(err, token);
      });
    },
    function(token, done) {
      User.findOne({ email: req.body.email }, function(err, user) {
        if (!user) {
          req.flash('error', "Couldn't find any user with given email address!");
          return res.redirect('back');
        }
        user.resetPasswordToken = token;
        user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
        user.save(function(err) {
          done(err, token, user);
        });
      });
    },
    function(token, user, done) {
      var email = {
        to: user.email,
        from: 'Yelp Camp <yelpcampapp@gmail.com>',
        subject: 'YelpCamp Password Reset',
        text: 'You are receiving this because you (or someone else) have requested the reset of the password for your account.\n\n' +
          'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
          'http://' + req.headers.host + '/reset/' + token + '\n\n' +
          'If you did not request this, please ignore this email and your password will remain unchanged.\n'
      };
      mailer.sendMail(email, function(err) {
        if(err) return next(err);
        req.flash('success', 'An e-mail has been sent to ' + user.email + ', with further instructions.');
        done(err, 'done');
      });
    }
  ], function(err) {
    if (err) return next(err);
    res.redirect('back');
  });
});
router.get('/reset/:token', function(req, res) {
  User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {
    if (!user) {
      req.flash('error', 'Password reset token is invalid or has expired.');
      return res.redirect('/signin');
    }
    res.render('reset', {
      user: req.user
    });
  });
});
router.post('/reset/:token', function(req, res) {
  async.waterfall([
    function(done) {
      User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) {
        if (!user) {
          req.flash('error', 'Password reset token is invalid or has expired.');
          return res.redirect('back');
        }
        user.password = req.body.password;
        user.resetPasswordToken = undefined;
        user.resetPasswordExpires = undefined;
        user.save(function(err) {
          req.logIn(user, function(err) {
            done(err, user);
          });
        });
      });
    },
    function(user, done) {
      var email = {
        to: user.email,
        from: 'yelpcampapp@gmail.com',
        subject: 'Your password has been changed',
        text: 'Hello,\n\n' +
          'This is a confirmation that the password for your account ' + user.email + ' has just been changed.\n'
      };
      mailer.sendMail(email, function(err) {
        req.flash('success', 'Success! Your password has been changed.');
        done(err);
      });
    }
  ], function(err) {
    res.redirect('/recipes');
  });
});
module.exports = router;

and here's my register route, to see how the password usually is stored in the db:

// Account creation logic
router.post("/register", function(req,res){
    if(req.body.password != req.body.passwordConfirm){
          return res.render("register", {error: "Les mots de passe ne correspondent pas."});
} else {
    if(validateEmail(req.body.email)){
        var email = req.body.email.toLowerCase();
    } else {
        req.flash("error", "L'adresse courriel est invalide.");
        return res.redirect("/register");
    }
    var newUser = new User({username: req.body.username, email: email});
    User.register(newUser, req.body.password, function(err, user){
        if(err){
            console.log(err);
            if(err.message === "No username was given"){
                req.flash("error", "Veuillez entrer un nom d'utilisateur.");
            } else if(err.message === "A user with the given username is already registered"){
                req.flash("error", "Le nom d'utilisateur que vous avez choisi est déjà utilisé.");
            } else if(err.message === "No password was given"){
                req.flash("error", "Veuillez entrer un mot de passe.");
            }
            return res.redirect("/register");
        }
        passport.authenticate("local")(req, res, function(){
            req.flash("success", "Bienvenue sur RecettesFlambées, " + user.username +".");
            res.redirect("/recipes");
        });
    });
    }
});

Thanks a lot!



via Davycodes

How to apply OO design patterns in a NodeJS project?

i'm doing a project in NodeJS about finantial control that uses a model for accounts (Class Accounts) which have some "private" attributes (_id, _name, _parent, _balance and _isDeleted) and some methods (get attributes..., set attributes...).

All created accounts (objects) are converted into a JSON and stored into a file (custom database), except their methods (only the attributes are passed to the JSON).

When i load the database file, i get the JSON containing all accounts and their attributes, and need to show them into a view page, using EJS engine.

But after converting into JSON and loading them they doesn't have their methods to get their "private" attributes anymore, and i couldn't think any way to get those info, except by using directly the attribute reference (like _id, _name ...).

How can i get those attributes according to OO design patterns, avoiding to make external references to private attributes of a class?

Thanks!



via Ighour

Bring an application forward by its title using node.js

I want to write some sort of window manager using Node and Electron.

Given I have the title of a given window, I'd like to be able to bring it forward (set as the active window).

I need it to work on both windows and linux.

I already found this https://github.com/thraaawn/winctl that does what I need but it's for windows only.



via Pascal Boutin

Getting error while running clubbed swift & react-native project on iOS device

I have an existing project written on swift and I have integrated react native to it everything is working fine on simulator but while running on device it give an error ie- Could not connect to the development server. Ensure - node server is running and available on the same network - run npm start from the react native root - node server URL is correctly set in AppDelegate

I have tried most of the method discuss over here github link

  • like changing the localhost to my laptop IP,
  • connecting device and laptop on the same network

but still i could not able to solve it, if i am missing any things kindly enlighten on comment or answer you valuable time will always be helpful

thank you



via Abdul Karim

Flightplan in Windows - Host key verification failed

I'm using flightplan to push my website up to a server. It works perfectly fine on my Mac. I tried to get it setup on my Windows computer, and finally got stuck.

First it was rsync, but I fixed that and have it working on windows. Now I'm getting Host key verification failed.

The part I can't figure out is that when I ssh in from a shell prompt on windows, I am good to go. It appears that I have it pointed appropriately to my .ssh directory as well.

Any help would be very appreciated



via BRogers

How do I redirect relative to the express application root?

I want to make my app so that it can be mounted at some location other than /. When I read the docs for express-4.x’s res.redirect(), it says I have three options:

  1. Absolute URI (http://example.org/path/nested)
  2. Host-relative (/path/nested)
  3. URI-relative (nested)

I don’t see any option for application-relative redirects.

Example of how an app might be mounted within another:

'use strict';

const express = require('express');

const app = express();
module.exports = app;

const subApp = express();
app.use('/subApp', subApp);

subApp.get('/blah/*', (req, res) => {
    if (/dee$/.test(req.url)) {
        res.end('end');
    } else {
        res.redirect('dee');
    }
});

How do I redirect to the root URI of subApp without requiring the code in subApp to know its mountpoint? Maybe there is a way I can construct it from information in req?



via binki

'This' is undefined in typescript even using arrow func in a promise

When I receive the 'catch' callback, 'this' is undefined, even using arrow funcitions. Any ideas?

private all(req: Request, res: Response): void {
    EntityRepository.getRepositoty(req.params.etName).then(repo => {

        ...

    }).catch((err) => {
        this.handleError(res, err); // here I get undefined.
    });
}

how the all func is called.

It's called based on a Express route.

constructor() {
    // Connect to database.
    DataAccess.connect();

    // Starts configuring routes for api
    this.router = Router();

    // Bad request due to absence of entity type.
    this.router.get("/", (req, res) => {
        res.statusCode = 400;
        res.statusMessage = SysMsgs.error.noEntityTypeSpecified.message;
        res.send();
    });

    this.router.get(this.routeBase, this.all);
    this.router.get(this.routeBase + "/:id", this.findOne);
}



via Leandro

How do you get data from form in Vue template?

I just want to send POST request to my server using fetch but since I'm kinda new to Vuejs I'm not sure how to get data from data. my pug code is like this below

<template lang="pug">
.wrapper
  .container
    h1 CNTRL
    form(v-on:submit.prevent='onSubmit').form
      input(type='text', placeholder='Username', v-model='id')
      input(type='password', placeholder='Password', v-model='password')
      button#login-button(type='submit') Login
</template>

This Is what I wrote on script section but It doesn't work. I don't know what's wrong with this.

export default {
    data () {
        id: '',
        password: ''
    },
    created () {
      // Set $route values that are not preset during unit testing
      if (process.env.NODE_ENV === 'testing') {
        this.$route = {
          name: 'landing-page',
          path: '/landing-page'
        }
      }
    },
    methods: {
        onSubmit() {
            fetch('/signup', {
                method: 'POST',
                body: JSON.stringify({
                    id: this.id,
                    password: this.password
                })
            })
        }
    },

  }



via Phillip YS

In Angular 2/4 why does my AuthGuard receive undefined from a function that is returning true? [duplicate]

This question already has an answer here:

My Authguard is receiving undefined from my function that is returning true.

My Authguard

@Injectable()
export class AuthGuardAdmin implements CanActivate{
constructor(private authService:AuthService, private router:Router){}

canActivate(){

 //console.log returns undefined
 console.log(this.authService.loggedInAdmin());

  if(this.authService.loggedInAdmin()){

    return true;
      } else {
         this.router.navigate(['/login']);
         return false;
        }
      }
  }

My logged in function. This function returns true, but the authguard gets undefined

loggedInAdmin(){

  this.getProfile().subscribe(profile => {
  this.user = profile.user, this.username = profile.user.username

    if (this.username=='pokeradmin'){

        //console.log returns true
        console.log(tokenNotExpired('id_token'));

        return tokenNotExpired('id_token');

     }else{
       console.log(false);
       return false;
     }

  });
}

I already debugged everything to see if it was a problem with the authservice, but it works fine. For some reason the loggedinadmin function is not returning true, but the console.log says its true



via harryd

static html served by Node express won't show on iphone

My first time to try some responsive design on desktop and iPhone at the same time.

I have successfully connected my iPhone(5s) with my Mac OSX (Yosemite) on my Mac's IP address. After creating a basic Node Express server, I confirmed that the "Hello World" response shows both on my desktop Chrome and iPhone Safari.

However, when I tried to serve static html files with app.use(), I can only see it on desktop Chrome. My iPhone Safari stopped to display anything. Could you help me identify the issue, please? Thank you very much!

Here's my file structure: file structure Here's my code: server index.js:

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

app.use(express.static(path.join(__dirname, '/../client/public')));
app.get('/', (req, res) => {
  // this commented part won't work either:
  // res.status(200).sendfile(path.join(__dirname, '/../client/public/index.html'));
  res.status(200).send('I\'m from server')
});

app.listen(8080, function() {
  console.log('iphone dev app listening on port 8080');
});

Here's my index.html:

<!DOCTYPE html>
<html>
<head>
  <title>iPhone</title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="./assets/js/index.js"></script>
</body>
</html>

Here's my index.js on my client side:

(function() {
  let app = document.getElementById('app');
  app.innerHTML = "I'm from js";
  console.log(app);
})();



via Alison Z

How can I start / stop a request stream with node.js?

I have

return request({
  method: "POST",
  url: response.stream.url,
  json: true,
  forever: true,
  body: {
    sessionid: response.stream.sessionid,
    symbols: symbolParams
  }
}).on("data", onData)

That gives me data whenever it comes through. But what if I want to STOP listening on that stream, how can I do that?



via Shamoon

laravel 5.4 package.json invalid

I am running homestead in vagrant on my windows 10 machine for Laravel 5.4. I was following the beginner laracasts (episode 14), which directed me to run npm install. I noticed my output was significantly shorter than the one in the tutorial, only listing

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules/chokidar/node_modules/fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

Upon further investigation, running npm show gave the error

npm ERR! Invalid package.json npm ERR! A complete log of this run can be found in: npm ERR! /home/vagrant/.npm/_logs/2017-05-27T23_01_22_283Z-debug.log

Here is the log referenced above:

0 info it worked if it ends with ok 1 verbose cli [ '/home/vagrant/.nvm/versions/node/v7.10.0/bin/node', 1 verbose cli '/home/vagrant/.nvm/versions/node/v7.10.0/bin/npm', 1 verbose cli 'show' ] 2 info using npm@4.6.1 3 info using node@v7.10.0 4 verbose stack Error: Invalid package.json 4 verbose stack at /home/vagrant/.nvm/versions/node/v7.10.0/lib/node_modules/npm/lib/view.js:84:30 4 verbose stack at /home/vagrant/.nvm/versions/node/v7.10.0/lib/node_modules/npm/node_modules/read-package-json/read-json.js:356:5 4 verbose stack at checkBinReferences_ (/home/vagrant/.nvm/versions/node/v7.10.0/lib/node_modules/npm/node_modules/read-package-json/read-json.js:320:45) 4 verbose stack at final (/home/vagrant/.nvm/versions/node/v7.10.0/lib/node_modules/npm/node_modules/read-package-json/read-json.js:354:3) 4 verbose stack at then (/home/vagrant/.nvm/versions/node/v7.10.0/lib/node_modules/npm/node_modules/read-package-json/read-json.js:124:5) 4 verbose stack at /home/vagrant/.nvm/versions/node/v7.10.0/lib/node_modules/npm/node_modules/read-package-json/read-json.js:311:12 4 verbose stack at /home/vagrant/.nvm/versions/node/v7.10.0/lib/node_modules/npm/node_modules/graceful-fs/graceful-fs.js:78:16 4 verbose stack at tryToString (fs.js:449:3) 4 verbose stack at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:436:12) 5 verbose cwd /home/vagrant/Code/Circles 6 verbose Linux 4.4.0-66-generic 7 verbose argv "/home/vagrant/.nvm/versions/node/v7.10.0/bin/node" "/home/vagrant/.nvm/versions/node/v7.10.0/bin/npm" "show" 8 verbose node v7.10.0 9 verbose npm v4.6.1 10 error Invalid package.json 11 verbose exit [ 1, true ]

I am no npm expert, but I cannot see any evident issues with the package.json. is one of the dependencies not valid or did I break something?



via Omega

success is fired before end response

As a beginner in web dev, I'm building my first web-app using pure node.js. In the registration part, the form data will be posted from the client-side to the server and then added to the database. The client, on success, will manipulate the DOM depending on the response it receives. However, the success callback is always fired before the response is sent.

client-side code:

$.post('/register.db', {
        data: JSON.stringify(user),
        contentType: "application/json",
        dataType: "text",
        success: function(data){
            alert(data);    // data is always undefined
            //...manipulate DOM
        }
});

server-side code:

var body = "";
req.on("error", function(){
      handleError();
}).on("data", function(chunk){
      body += chunk;
}).on("end", function(){

      // success is fired when request ends rather than response ends

      var user = JSON.parse(qs.parse(body).data);
      console.log("user ",user);
      res.on('error', function(err){
           handleError();
      });
      //...send data to database and write response... 
});

Could any kind soul please point out where I did wrong? I would appreciate it a lot!!



via LillyJ

How to see what exactly is request from the request module sending?

I am trying to login to a server using Node.js request module. The server refuses that request.

What can I do to get exact plaintext data of the request the request(options, callback) or request.post(options,callback) is sending?



via Tomáš Zato

How to load changes instantly - React Native

Question

How do I load new data every time it is added to the server?

What I would like to have happen

  • User opens app
  • User uploads text to server
  • The app displays the text from the server immediately

What is currently happening

  • Users uploads text to server
  • User reloads app
  • The app displays the text from the server

Server Side

I am using expressJS for the server and then I am saving all of the text that the server gets to an off-site mongoose DB.

More info

  • I am using a Node JS server

  • I am using the fetch API to communicate between the server and the client

  • The client app is written with React Native



via pudility

Reverse matching Express routes to database entries

I'm trying to build a sort of database-based ACL for my Express application. I currently have a Permissions table in the database that contains something like that:

  • Resource: *
  • Method: *
  • RoleID: 1
  • isAllowed: true

  • Resource: /users
  • Method: GET
  • RoleID: 2
  • isAllowed: false

  • Resource: /users/id/*
  • Method: GET
  • RoleID: 2
  • isAllowed: true

My aim is to build a middleware that checks on the request object and allows or denies the route based on the rules in the database. My practical problem is, how do I match, say /users/id/1 with the database entry /users/id/*? If I use the database entry as the basis for my regex, then /users/id/1 is clearly matched, however, I don't think it's practical to pull and test ALL database entries for each request. What do you think would be the best approach to obtain the right rule from the database based on the requested URL?

Thanks for your time!



via finferflu

Node readline 'line' event not firing

I am creating a this program which finds the common words of 2 word files and then creates a new file with just the common words. I'm using the readline module to read each word of first word file and then store that word in a Trie. After that has been completed, I'm trying to read the words from the other word file and if it is in trie, I'm writing to file.

I'm using promises to make sure that the events happen in sequence but the second time the 'line' event is not triggered.

'use strict'
const readLine = require('readline');
const fs = require('fs');

const wordList = require('./Trie.js');

function createTrie(reader, trie) {
  return new Promise((resolve, reject) => {
    if(typeof reader === 'undefined' || reader === null)
      reject('Failed')

    reader.on('line', line => trie.add(line))
    reader.on('close', () => {
      console.log('done')
      resolve(trie)
    })
  })
}

function findCommon(reader, trie) {
  return new Promise((resolve, reject) => {
    if(typeof reader === 'undefined' || reader === null) {
      console.log('failed')
      reject('Failed')
    }

    let commonWords = ''

    console.log('we are here')

    reader.on('line', (line) => {
      console.log(line) // This does not output
      if(line.length > 2 && trie.search(line)) {
        let word = line + '\n'
        commonWords += word
      }
    })
    reader.on('close', () => {
      fs.writeFile('wordlist.txt', commonWords, (err) => {
        if(err) {
          console.log(err)
          reject('error')
        }
        console.log('written')
        resolve('Success')
      })
    })
  })
}

let reader_1 = readLine.createInterface({
  input: fs.createReadStream('words/enable2k.txt')
})
let reader_2 = readLine.createInterface({
  input: fs.createReadStream('words/engmix.txt')
})

createTrie(reader_1, wordList)
  .then((trie) => findCommon(reader_2, trie))
  .then((data) => console.log(data))

The above code gives the below output

done
we are here

The 'line' event is not triggered. It seems like I'm not using readline correctly but I'm not sure.

Any help is appreciated!



via Utkarsh

How to implement form-based authentification without SSL/TLS

I am building a small website to learn web development.

I would like to have a secure authentication system. After some reading, it seems like there is no way to send the credentials to my server without SSL/TLS connection.

However, an SSL connection is not suitable for me for the following reasons:

  • It is complex;
  • It is (most likely) not free

Is there any alternative that I could use for this purpose ?



via acourchesne

node js request multiple urls same time

I want to request multiple urls with npm s request library and return results in on json

my code is that but not working.

request({
    url: "https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&videoId="+item+"&key=AIzaSyCPv-dasd&maxResults=100&",
   url: "https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&videoId="+item+"&key=AIzaSyCPv-dasd&maxResults=100&",
    json: true
}, 



via user8026867

How to remove array item if exists or push if not?

I would like to add the item if it is not in the array. I would like to remove the item if it is in the array.

collection.update(
    {id: req.user, going: {$nin: [req.body.id]}},
    {
        $addToSet: {going: req.body.id}
    }
);

collection.update(
    {id: req.user, going: {$in: [req.body.id]}},
    {
        $pull: {going: req.body.id},
    }
);

These are correct. But if I run both of them it adds and removes one fast.



via Markus Ivancsics

How to call DLL which depends on WIN32 API from node.js running on Linux?

I have a web application running on windows 7 x64 and I'm trying to port it to linux ubuntu 16.04 x64. The setup comprises node.js and uses edge.js library to interface with .NET DLLs of my own and a third party DLL.

The .NET DLLs don't have dependencies outside .NET Framework. I don't have access to the third party's DLL code, but running it through dumpbin.exe I know it depends on WIN32 DLLs like kernel32.dll, gdi32.dll, advapi32.dll, and others alike. In windows the third party DLL required registration through regsvr32.exe and it had to be copied to c:/windows/system32 folder. It also required an interop.DLL assembly generated with tlbimp.exe, wich is referenced from a wrapper DLL.

node.js -> edge.js -> wrapper1 (.NET DLL) -> interop.DLL -> third party DLL -> WIN32 APIs
                  |
                  `-> wrapper2 (.NET DLL) ----------------> my own .NET DLL

So far I've accomplished running the node.js server on linux and interfacing through edge.js with the .NET DLLs of my own (had to install mono).

But I was not able to interface with the third party DLL. I used wine to register the thrid party DLL (wine64 regsvr32 thirdParty.dll) and copied it to ~/.wine/drive_c/windows/system32. But I don't know how to call it from the node.js/edge.js/wrapper1 running on linux. In windows, as the third party DLL is registered, the interop.DLL just finds it, but this seems improbable with linux/wine.

How should I call the third party DLL depending con WIN32 API from node.js running on linux?



via Ale

variable value becomes undefined in NodeJS after if cycle

HI I have some code to get a json value from my db and then add it to an object but in my if cycle it has the value {"isRoot": "true", "visible": "true"} but after the cycle i do a console.log to this and get undefined...

Database.Services.getServicesMapInfoById(device.id).then(function(mapData){
            if(mapData!=undefined){
                map = mapData.map;
                console.log("sendDeviceInfo getServicesMapInfoById map  >>>>>>>>>>>>>>>>>>>>> ", map);
                console.log("sendDeviceInfo sendData.map >>>>> ", map);
                console.log("end if ");
                return resolve(map);
            } 
        }).catch(function (e) {
            createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'sendDeviceInfo','FATAL',e);
            return reject(e);
        });
        console.log("sendDeviceInfo map --------------------------------->",map);
        if(map!=null){
            console.log("sendDeviceInfo map != null");
            sendData.map=map;
        }

Logs:

sendDeviceInfo getServicesMapInfoById map  >>>>>>>>>>>>>>>>>>>>> {"isRoot": "true", "visible": "true"}

sendDeviceInfo map ---------------------------------> undefined

Can anyone help me? I'm returning the value of map with Promises using resolve but this didn't solve my problem...



via Catia Matos

gRPC authentication with metadata

I'm wondering how I can get authentication setup on my gRPC service? I've read that metadata is the way to go.

Using the Node.js grpc library and grpcc to test my implementation. I basically have a JWT token being received on every request, just no way to digest and validate it over the gRPC pipe.

Suggestions/guidance is most appreciated.



via ddibiase

How to change scope back to original function after calling a “local” function within module.exports in Node.JS

I am trying to call another local function 'MessageScoring' within another function 'NextMessageCalculation' which are both in module.exports, however I am having trouble with getting the scope to change back. The function successfully calls the other local function, however the scope is then changed and variables in the previous scope all return undefined now. How would I fix this or is there a better way to call the local function to avoid this?

module.exports = {
   MessageScoring: function()...

   NextMessageCalculation: function(){
              console.log(d[i]['id']); //returns correct value
              var score = module.exports.MessageScoring(doc[i].attr_list,user_data);
              console.log(d[i]['id']); //returns undefined now
   } 
}



via Austen Novis

Uploading image with mongodb node.js and mongoose

I want to be able to upload an image from his computer to the server and the image to be saved in my mongoose schema and also be able show it back to the user. Here is my schema

var mongoose = require("mongoose");

var blogSchema = new mongoose.Schema({
  title: String,
  image: String,
  body: String,
  category: String,
  author: {
  id: {
     type: mongoose.Schema.Types.ObjectId,
     ref: "User"
  },
  username: String
  }, likes: [
  {
     type: mongoose.Schema.Types.ObjectId,
     ref: "likes"
  }
  ],
  comments: [
  {
     type: mongoose.Schema.Types.ObjectId,
     ref: "Comment"
  }
],
created: {type: Date, default: Date.now}
});

module.exports = mongoose.model("Blog", blogSchema);



via fanffis theologiths

ReferenceError: window is not defined after Ajax call trying to redirect the user

I am new to express with EJS.

I tried making a ajax post request for submitting to the values to the DB using.

 $.ajax({
    type: 'POST',
    url: '/register',
    data: user,
    success: function(data){
        console.log(data);
        return data;
    }
  });

  return false;

This call is successful and after which the control goes to the calling function

var sess;

  app.post('/register',urlencodedParser,function(req,res){
    sess=req.session;
    var newUsr=Users(req.body).save(function(err,data){
      if(err) throw err;
      console.log(" back from ajax with data :::; " + data);

      console.log("step1 cleared");
      sess.registered=true;

    });
    console.log("step2 cleared");
    location.window.href = '/index2';
  });

I want the user to see the index page once the registration is successful, but I am getting the below error.

ReferenceError: location is not defined

I think location object is not there in node, thus this error, but again I dont know how to fix this issue, please suggest



via Saurabh Jhunjhunwala

render React component from a string

I have some React code in the string, for example:

const component = `
function App() {
  return (
    <div>
    test
    </div>
  );
}
`;

And I want to be able to render that component from within browser, something like:

import React, { Component } from 'react';
import { render } from 'react-dom';
import * as babel from 'babel-standalone';


const babelCode = babel.transform(component, { presets: ['react', 'es2015'] }).code;

render(eval(babelCode), document.getElementById('WorkFlow'));

This particular example doesn't work but it shows what I'm looking for, any help appreciated!

Thanks!



via Sarkis Arutiunian

Express.js Server with iOS Swift Request Timing Out

I am trying to make an HTTP POST request using an iOS Swift app to an Express.js server. In the post request, I send JSON data, creating the JSON object using a dict and SwiftyJSON. However, the request continues to time out. I think it has something to do with 'body-parser', which is what I am using to parse the HTTP body. Here is my swift code:

    override func viewDidLoad() {
    super.viewDidLoad()


    var dict  = ["name": "FirstChannel", "verified": 0, "private": 1, "handle": "firstChannel", "subscribers": 0] as [String : Any]
    var jsonData = JSON(dict)

    do {
        let post:NSData = try jsonData.rawData() as NSData
        var postLength: NSString = String(post.length) as NSString
        var url = URL(string: "http://10.0.0.220:3000/channel/createChannel")!
        var request = NSMutableURLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = post as Data
        request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")

        NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main, completionHandler: { (resposne, data, error) in
            if(error != nil) {
                print(error)
            }
            else {
                print(data)
            }
        })



    }
    catch {
        print(error.localizedDescription)
    }
}

And here is the code I use in my express.js router:

var express = require('express');
var router = express.Router();
var http = require('http');
var url = require('url');
var util = require('util');
var bodyParser = require('body-parser')
var ObjectID = require('mongodb').ObjectID;

router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended = true}));

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_db');

var channelSchema = mongoose.Schema({
  name: String,
  verified: String,
  private: String,
  channelID: String,
  handle: String,
  subscribers: String
});

var Channel = mongoose.model("Channel", channelSchema);
router.post('/createChannel', bodyParser, function(req, res, next) {
    req.body = true;
    if(!req.body) return res.sendStatus(400);
    var objID = new ObjectID();

    var newChannel = new Channel({
       name: req.body["name"],
       verified: req.body["verified"],
       private: req.body["private"],
       channelID: objID,
       handle: req.body["handle"],
       subscribers: (req.body["subscribers"])
  });

newChannel.save(function(err, point){
  if(err) console.log(err);
});

});

If anybody could help me out and help this POST request succeed, I would greatly appreciate it. Thanks!



via Aidan Kaiser

Accessing and communicating with javascript programm with node.js

I've been working on a Connect Four AI for a Raspberry Pi robot project and so far everything seems to be working. The programm creates a "Game" object that contains all the relevant functions like "placeCoin" or "aiMove" etc.

I now however face the problem of how to access this programm from "outside". I would like it to work on a Raspberry Pi with a Linux OS installed. For this purpose I have set it up for node.js. Using the Windows command prompt, I can execute the entire program with "node connect-four.js".

This is not what I need though. For my purposes, I need to start the programm by creating the "Game" object and then keep it "open" so to speak. I then want to be able to externally call the needed functions within my programm like "aimove" and then receive a returned value to further communicate with the actual robot. During this time, I would like the programm to wait.

How would I go about setting up this kind of communication?

Thanks in advance for your help!



via Kaza123

Mongoose update query keeps on inserting data with upsert true without updating and adding only 1 field

I am working on Facebook login in Node js with Mongoose. i am getting issues while updating data.

This is my Scheme file

var mongoose = require('mongoose');


var Schema = mongoose.Schema;

 // Schema
var RegSchema = mongoose.Schema({
    UserName: String,
    UserEmail: String,
    userprofileImage : String,
    userId: String,
    reg_time : {
        type : Date, default: Date.now
    }
}, { collection: 'user' });

// Model
module.exports = mongoose.model('UserReg', RegSchema);

and this is my main file where update and insert(if not found) is placed

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); 



var UserReg = require('./myschema.js');

module.exports = function(userdetail, callback){
var bb;

                  var UserAdd = new UserReg({
                                "UserName": userdetail.username,
                                "UserEmail": userdetail.useremail,
                                "userId": userdetail.userId,
                                "userprofileImage": userdetail.userprofileImage
                            });

                    var userdetailchange = {
                                "UserName": userdetail.username,
                                "UserEmail": userdetail.useremail,
                                "userId": userdetail.userId,
                                "userprofileImage": userdetail.userprofileImage
                    };

                    // Update if found otherwise Insert
                    UserAdd.update({"userId":userdetail.userId },{ $set:userdetailchange, $setOnInsert:userdetailchange ,upsert:true, new: true, setDefaultsOnInsert: true}, function (err, data) {
                            if (err) {
                                callback(err);
                            } 
                                callback(data);                             
                    });

};

Now it keeps on inserting user data in collection with only 1 field which is userId and also a default _id field. Please help me in updating whole data if match found or Insert whole data in Collection. Any help will be highly appreciated.



via noobcode

express app handles 404 before forthcoming routes. Not all existed routes are detected by express.Router in time

here is app.js file:

var express = require('express');
var routes = require('./routes/index');
app = express();

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

and routes/index.js:

var express    = require('express')
, router       = express.Router()
var importer = require('./../lib/importer')
    , importRoutes = importer(__dirname)
    , routes = {
        views: importRoutes('./views')
    };

router.get('/login', routes.views.login.get);
router.post('/login', routes.views.login.post);
router.get('/register', routes.views.register.get);
... and many other routes (more than 50)
router.get('/register', routes.views.auth.oneOfTheLastRoutes.get);
module.exports = router;

BUT if I go to localhost:3000/oneOfTheLastRoutes or some route from the bottom the app responses 404, even this route really exist in routes/index.js, and if I move this route higher in the module the app will give correct response.

I'm almost sure that the matter is in lib/importer.js where some async code requires all routes from the routes/views folder, and not all routes are assigned to rotutes.view property.

var fs = require('fs');
var path = require('path');
function dispatchImporter (rel__dirname) {

    function importer (from) {
        //console.log('importing ', from);
        var imported = {};
        var joinPath = function () {
            return '.' + path.sep + path.join.apply(path, arguments);
        };

        var fsPath = joinPath(path.relative(process.cwd(), rel__dirname), from);

        fs.readdirSync(fsPath).forEach(function (name) {
            var info = fs.statSync(path.join(fsPath, name));
            //console.log(name);
            if (info.isDirectory()) {
                imported[name] = importer(joinPath(from, name));
            } else {
                // only import files that we can `require`
                var ext = path.extname(name);
                var base = path.basename(name, ext);
                if (require.extensions[ext]) {
                    imported[base] = require(path.join(rel__dirname, from, name));
                } else {
                    console.log('cannot require ', ext);
                }
            }
        });

        return imported;
    }

    return importer;
}

module.exports = dispatchImporter;

AND I didn't managed to come up with a solution, where all route files would be required and assigned to routes object before the 404 handler.

the structure of files is as follows:

app.js
lib/
   importer.js
routes/
   index.js
   views/
      login.js
      register.js
      etc...



via Nozim

node_acl: store acl globally to access from different modules

I'm trying to use acl within my node/express application.

My current main goal is to instantiate node_acl with a mongo backend and store it in a global place to consume it later on.

My current solution looks like:

server.js:

The application connects with mongodb and initialises acl and the routes.

mongoose.connect(config.db, (err, db) => {
   // initialize acl
   aclConfig(mongoose.connection.db);

   // initialize api
   routesConfig(app);
});

aclConfig()

Instantiation of acl and to store it in aclStore. Later we try to access this stored data.

import Acl from 'acl';
import aclStore from '../helper/acl-store';

export default(dbConnection) => {

    let acl = new Acl(new Acl.mongodbBackend(dbConnection, 'acl_'));

    // Set roles
    acl.allow([
        {
            roles: 'admin',
            allows: [
                {resources: '/adminonly', permissions: '*'}
            ]
        },
        {
            roles: 'user',
            allows: [
                {resources: '/api/events', permissions: 'GET'}
            ]
        }
    ]);

    aclStore.acl = acl;
}

AclStore

Just a basic class to set/get the acl.

class AclStore {
    constructor() {
        this._acl = null;
    }

    set acl(acl) {
        this._acl = acl;
    }

    get acl() {
        return this._acl;
    }
}

let aclStore = new AclStore();

export default aclStore;

I expected to be able to get my created instance from everywhere I want, by importing the aclStore and accessing acl. The solution does not work, if I try to apply aclStore.acl.middleware() on a route, see here:

import express from 'express';
import ctrl from './auth.ctrl';
import aclStore from '../../helper/acl-store';

const router = express.Router();

router.route('/adminonly')
    .put(ctrl.login, aclStore.acl.middleware());
    // --> TypeError: Cannot read property 'middleware' of null

export default router;

It returns:

TypeError: Cannot read property 'middleware' of null. It looks like it is instantiated before the data were set in aclConfig().

For me it looks like a "Timing issue", i.e. when I try to get aclStore.acl the aclConfig() method (intatiates acl and stores it in aclStore) is not executed yet.

I've found out that I have access to aclStore.acl if I would use it within the route controller ctrl.login(), i.e. data are stored properly in aclStore.

I'm trying to achieve the same solution like in this stackoverflow question, but in my case I've to handle it with a mongo db backend, i.e. I've to connect to mongodb first and use the db information data to instantiate acl.



via mbppv

Pass 'this' to a class variable inside constructor

I am interested, how to pass this to a class variable inside a constructor of a parent, so I could use parents methods and access other variables of the parent and call their methods?
Here is my parent class:

var async = require('async');
var Rater = require('./rater')
var Similars = require('./similars')
var Suggestions = require('./suggestions');

module.exports = class Engine {
    constructor() {
        this.likes = new Rater(this,'likes');
        this.dislikes = new Rater(this,'dislikes');
        this.similars = new Similars(this);
        this.suggestions = new Suggestions(this);
    }

And here is the example of usage and where is get the following error:

Cannot read property 'engine' of undefined
at --\\classes\rater.js:89:19


module.exports = class Rater {
  constructor(engine,kind) {
    this.type = kind;
    this.engine = engine;
    if(kind == 'likes') //database schemes
      this.db = Likes_db;
    else if(kind == 'dislikes')
      this.db = Dislikes_db;
    else if(kind == 'similars')
      this.db = Similars_db;
    else if(kind == 'suggestions')
      this.db = Suggestions_db;
  }
  //..
  //other methods
  //..
  remove(user,item,done) {
      this.db.remove({user: user,item: item},(err) => {
        if(err)
          return done(err);
        async.series([
          function(done) {
              this.engine.similars.update(user,done); //error-cant enter the method
          },
          function(done) {
            this.engine.suggestions.update(user,done);
          }
        ],function(done) {

        });
    });
  }
}



via user115

PHP with socket.io or recreate everything in node.js and socket.io?

I'm currently planning on coding a private project, to be more specific a virtual chat room, where avatars can walk around chat.

Now I'm literally a little confused, which language should be used to code it in. For now I've used PHP for the backend things, such as authentification and HTML for the frontend.

But i know i will need to use Javascript, to draw the chatroom assets to a canvas element. And i will need to use socket.io (node.js) for the chat and the packets.

Now my question, can I even use PHP in the backend and use socket.io for the communication between the server and the client and the chat itself?

For now the process is the following:

  1. User logs into a account, the background check is done in php
  2. User gets redirected to a Dashboard
  3. User selects the menu point world
  4. User selects a chat world and gets redirected to another site which contains a canvas and a chatbox

Screenshot of step 3: Select world

Screenshot of step 4: Canvas with chatbox

How could I create a socket after building the canvas to use socket io to communicate with the server and to create the chat application?

Would it be easier to code the whole site without PHP and just using node.js and socket.io (Also for the user autentification etc) ?

I appreciate any kind of suggestions and help



via d4neZworldQuestions

How do I assign a sqlite3 database result into a global variable

I have this code:

var query = 'SELECT postName FROM post WHERE id = ' + id;

db.get(query, function dato(err, row) {
    if (err){
        console.log(err);
    }else{
        console.log(row.postName); // works!
        return row.postName;
    }
});

Can you help me to know the way for store row.postName into a global variable?



via estebancito

Were to put the body callback from the request.get

I try to get the HTML from the website but is not render on the server anything only on the console

_body how to get the HTML from this site and were to put this body callback

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



request.get('https://tesla.com/home', function (err, response, _body) {
  // access data from other web site here
  console.log(_body);




  var server = http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write(_body);
    response.end();
  });

  server.listen(3000);
  console.log("Server is listening");


});



via George

Can't resolve module.js

I have the following directory structure:

package.json
project
  src
    webpack.conf.js
    index.js

I want to be able to run webpack --config project/src/webpack.conf.js from the root level, but it gives me errors, either that it can't resolve the entry file, or can't resolve module.js from webpack node_modules folder.

My webpack.conf.js:

module.exports = {
  context: process.cwd() + "/project",
  entry: "./src/index.js",
  target: "node",
  resolve: {
    extensions: ['.js'],
  }
};

It works perfectly when I run it from project location, but doesn't work when I run it from root. What's wrong?



via user99999

Access a node.js server from a separate network

I'm trying to create a simple live chat using node.js, socket.io and express. I've gotten this to run over the IP address of my network so multiple machines can access it, but is there a way for someone else to connect through an entirely different internet connection without me paying for server space or getting a static IP? Thanks for any help



via Fool

How does one set up (database, or other) context in a GraphQL resolver?

The GraphQL docs give an example of a resolver function that accepts an argument called "context".

They have to say this about it -

context A value which is provided to every resolver and holds important contextual information like the currently logged in user, or access to a database.

And their code example looks like this -

Query: {
  human(obj, args, context) {
    return context.db.loadHumanByID(args.id).then(
      userData => new Human(userData)
    )
  }
}

This seems to me a perfectly natural pattern to want database access inside a resolver function, and unsurprisingly it is what I need to do.

This database context is not set up automatically, obviously, since GraphQL is completely agnostic about your particular means of data persistence.

My question is, how does one configure this context to provide one's specific db interface? I can't find mention of this in the tutorials/docs, or anywhere really.



via metahamza

node wildcard filename soundcloudjs

hi have daily recorded files to upload on soundcloud with cron on my directory record like Mike_27_05_2017_12_04_30.mp3

Tom_27_05_2017_10_00_00.mp3

how can i add the filename with wildcard automatically

the wildcard code not work asset_data: __dirname + '/record/Tom_*.mp3'

the code work asset_data: __dirname + '/record/Tom_27_05_2017_10_00_00.mp3'};



via Ambassador

npm module for clarifai not found when I start the node server

module.js:341
    throw err;
    ^

Error: Cannot find module 'clarifai'
    at Function.Module._resolveFilename (module.js:339:15)
    at Function.Module._load (module.js:290:25)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/Users/shiva/seefood-backend/app.js:4:16)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)

I get the above message in terminal when I do node app.js. I have installed Clarifai npm package as mentioned on https://developer.clarifai.com/quick-start/ with npm install clarifai but it still gives me this error. Do I need to install the package globally? Also this is my app.js :

var express = require('express')
var app = express();
var bodyParser = require('body-parser')
var Clarifai = require('clarifai')
var secrets = require('./secrets')
var keys = secrets.clarifaiConfig()

app.use(bodyParser.json());

var ClarifaiInstance = new Clarifai.App(
  keys.access_key,
  keys.secret_key
)

var store

var foodModel = 'bd367be194cf45149e75f01d59f77ba7'
var fnol = function getPredictionAsJSON(imageURL) {
  ClarifaiInstance.models.predict(foodModel, imageURL).then(
    function(response) {
      store = response.outputs[0].data
      console.log(store + ' from inside the fn');
    },
    function(err) {
      console.error(err);
    }
  );
  return store
}

app.listen(8000, function () {
  console.log('Recognize app listening on port 8000!')

  app.post('/classify', function(req, res) {
    var clarifaiData
    var imageURL = req.body.imageURL
      clarifaiData = fnol(imageURL)
      // console.log('cldata : '+ clarifaiData)
      var responseObject = {imageURL: imageURL, data: clarifaiData }
      // console.log('rObj : '+responseObject)
      res.send((responseObject));
  });

  app.get('/classify', function(req, res) {
    res.json((store));
  });
})



via ShivaV

How can I make use of weak references in javascript?

I have some very large objects that are used intensively, but occasionally in my Node.JS program. Loading these objects are expensive. In total they occupy more memory than I have in the system.

Is there any way to create a "weak reference" in Javascript, so that the garbage collector will remove my objects when memory is low, and then I can check whether the object is and reload it again if it was garbage collected since my last access?



via Bjorn Reppen

Query top level array of subdocs with MONGOOSE, to only return N most recent subdocuments in array

I'm looking for the conditions, fields, etc that i would need in a query, or an async flow to query a single document which has an array of subdocuments at the top-level.

Model:

let postSchema = new mongoose.Schema({
    date : {type: Boolean, require: true},
    message : {type: String, require: true}
});

let Post = new mongoose.Schema({
    locid: {type: String, unique: {indexed: true}, require: true},
    posts : {type: [postSchema], require: false}
});

Essentially, I would provide a Locid value as shown above into a function that i'm hoping would look like this:

Post.methods.getLastTwentyPostsForOne = function (locid) {
    return new Promise(function (values, error) {
        let p = new Post();
        p.find({"locid" : locid}, {/*...the conditions and elements here...*/}).exec()
            .then(function (found) {

                //..would return the last 20 posts, or less if there are less...

            }, function (err) {
                //..handle errors..
            })
    })
};

The most basic way i can think of doing this, would be to just fetch the whole array, and since mongo stores entries one after the other chronologically, to just parse the array and appending the last 20 or less posts contained in it into a final array (with a second promise-based function).

this makes the previous method, look like this:

function returnLastTwenty(posts) {
    return new Promise(function (results) {
        if (posts.length === 0) {
            return results([]);
        }
        if (posts.length <= 20) {
            return results(posts);
        }
        let length = posts.length;
        var next = [];
        for (i = length - 21; i < (length -1); i++) {
            next.append(posts[i]);
        }
        if (next.length === 20) {
            return results(next);
        } else {
            console.log('Some Error: found more than 20 posts, but parsed less');
            return results(next)
        }
    });
}

Post.methods.getLastTwentyPostsForOne = function (locid) {
    return new Promise(function (values, error) {
        let p = new Post();
        p.find({"locid" : locid})
            .then(function (found) {
                if (found.length === 1) {
                    returnLastTwenty(found[0].posts)
                        .then(function (results) {
                            return values(results)
                        })
                } else {
                    return error("Didn't find a unique document for locid: " + locid);
                }
            }, function (err) {
                return error(err)
            })
    })
};

While this does work.. the for loop and second async method seems too much.. Any clues as to how to achieve this with mongoose with a single query?



via murphguy

NodeJS read huge directory file by file

I have a directory composed of empty files and I want to iterate through each of their names. However I have nearly 20 million of these empty files and to load them all into memory with fs.readdir or fs.readdirSync would both take needlessly long and devour all my memory on the system.

What would be a way to go about this?

Ideally I would look for something that reads file by file in an async fashion with code that would ressemble the following:

readdirfilebyfile((filename)=>{....}) so that at no point would I keep the entire list of files in memory.

The current solution I am using is dumping all the file names into a single file which I then read as a data stream. However, this is just running away from a problem that I should know how to solve without resorting to this.



via Slava Knyazev

Webpage loads forever when file can't be found

I have a simple Express.js/Node.js website. If a file can't be found, the server is supposed to send a 404 error. But it doesn't work as expected. Let's say, if an image has the wrong URL, the webpage which the image is on will just keep on loading forever. How do I set up the error handlers properly so it stops loading if it detects a file doesn't exist?

This is my JavaScript:

var express = require('express'); // Express.js
var app = express();
var http = require('http');
var server = http.createServer(app);
var bodyParser = require('body-parser');
var postgres = require('pg'); // Postgres database

app.use(express.static('static', {
    extensions: ['html']
}));



app.all('*', function (request, response, next) {
    var redirectURL = request.query.redirect;
      if (redirectURL != undefined) {
        response.redirect(redirectURL);
      }
});

app.get('/', function (request, response, next) {
  response.redirect('/main/index');
});



// Handle 404 error
app.use(function(request, response) {
    response.status(400);
    response.send("Error 404!");
});

// Handle 500 error
app.use(function(error, request, response, next) {
    response.status(500);
    response.send("Error 500!");
});



server.listen(process.env.PORT || 8080, function () {
  console.log('Listening on port 8080!');
});



via repfarmer

return filename of uploaded file with multer and nodejs

I am creating a simple application as a learning experience with ionic 2 that connects to a node server running multer to upload images. The problem I am running into is, I need to get the final file name from multer back to the app that uploaded it, to save it locally. I am using the Auth and User modules from @ionic/cloud-angular for authentication and user information. The User object has a details object with things like "name", "email", "username", "image", ... So, when an image is uploaded to the node server and multer saves it, I need to get that filename back to the application so I can update the user.details.image property.

Here is a simple version of my node server...

var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');
var multer = require('multer');
var cors = require('cors');
var postStorage = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, './uploads');
    },
    filename: function(req, file, callback) {
        let fileName = '', postName;
        if(typeof req.body.postName !== "undefined") {
            postName = req.body.postName.toLowerCase().replace(/ /g, '-');
            filename += postName;
        }
        fileName += new Date().getTime();
        fileName += ".png";
        callback(null, fileName);
    }
});
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cors());
app.post('/upload', function(req, res) {
    var uploadPost = multer({storage: postStorage}).single('post_image');
    uploadPost(req, res, function(err) {
        if(err) {
            return res.end("error uploading file");
        }
        res.end("file uploaded");
    });
});
app.listen(app.get('port');
console.log("app listening on port: " _ app.get('port'));

Is there a way to have it send back the final file name that multer saved? Something like res.json({fileName: fileName}); res.end(); I really don't know at this point, and all the tutorials I can find on multer just show how to create a new filename and save a file in disk or database or memory, but nowhere does it show how you can actually get that filename back to the application that uploaded it. Thank you in advance for any help, I really appreciate it. If you need to see the ionic 2 code that uploads the stuff please let me know and I will update the post with that code as well. Thank you.



via Neglected Sanity

Jest Testing with require modules: ejs-loader

I am playing with the idea of having large static html bundles just loaded into a react component vice typing them all out in jsx. I am currently just experimenting with ejs-loader and html-react-parser to evaluate the feasibility of this. Everything actually renders fine but I cannot get any tests to work with jest for this. I receive: 'Cannot find module 'ejs-loader!./AboutPage.view.ejs' from 'AboutPage.js'' errors and I am unsure of what to do.

I am currently just working off of react-slingshot as my base for experimenting with this.

The component itself is simple:

import React from 'react';
import Parser from 'html-react-parser';
import '../styles/about-page.css';

const view = require('ejs-loader!./AboutPage.view.ejs')();

// Since this component is simple and static, there's no parent container for it.
const AboutPage = () => {
  return (
    <div>
      {Parser(view)}
    </div>
  );
};

export default AboutPage;

And the test is:

import React from 'react';
import {shallow} from 'enzyme';
import AboutPage from './AboutPage';

describe('<AboutPage />', () => {
  
  it('should have a header called \'About\'', () => {
    const wrapper = shallow(<AboutPage />);
    const actual = component.find('h2').text();
    const expected = 'About';

    expect(actual).toEqual(expected);
  });
  
});

I have read through the docs and similar questions like this. I attempted to use a custom transformer, but I may be misunderstanding something as it doesn't appear to be even called.

Package.json

"jest": {
    "moduleNameMapper": {
      "\\.(css|scss)$": "identity-obj-proxy",
      "^.+\\.(gif|ttf|eot|svg|woff|woff2|ico)$": "<rootDir>/tools/fileMock.js"
    },
    "transform": {
      "^.+\\.js$": "babel-jest",
      "\\.(ejs|ejx)$": "<rootDir>/tools/ejx-loader/jest.transformer.js"
    }
  },

and the transformer itself:

module.exports = {
  process(src, filename, config, options){
    console.log('????');
    return 'module.exports = ' +  require(`ejs-loader!./${filename}`);
    //return require(`ejs-loader!./${filename}`);
  }
};


via AndrewHunter

Control multiple BLE peripherals with one central

I am pretty new to IoT and BLE. What I want to achieve is to write on GATT characteristic of at least 100 peripheral devices simultaneously or in a very short period of time(i.e. less than 100ms). Currently my peripherals are Ble nano (nRF51822) with custom GATT service running on them. I am using my Mac as central BLE. I am using Node.js and noble to implement the central. I want to know if such thing is possible at all and if possible, please link me to an example code. :)



via Goris

NodeJS and robots.txt that returns ContentType -> text/html

I try to set robots.txt file in ExpressJS. I found that to make all fine needed to add middleware function into app.js . But all time when i test my robots.txt i get ContentType = text/html . What i do wrong?

// app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

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

var app = express();

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

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

app.get('/robots.txt', function (req, res) {
    res.type('text/plain');
    res.send("User-agent: *\nDisallow: /engine/go.php\nDisallow: /engine/download.php\nDisallow: /user/\nDisallow: /newposts/\nDisallow: /statistics.html\nDisallow: /*subaction=userinfo\nDisallow: /*subaction=newposts\nDisallow: /*do=lastcomments #comments into text\nDisallow: /*do=feedback\nDisallow: /*do=register\nDisallow: /*do=lostpassword\nDisallow: /*do=addnews\nDisallow: /*do=stats\nDisallow: /*do=pm\nDisallow: /*do=search\n\n# comment in text\n\nUser-agent: Yandex\nDisallow: /*sid= # comment\nDisallow: /*do=addnews\nDisallow: /*do=stats\nDisallow: /*do=pm\nDisallow: /*do=search\n\nUser-agent: Googlebot\nDisallow: /newposts/\nDisallow: /statistics.html\nDisallow: /*subaction=userinfo\n\n# some more comments\n# and one more comment");
});

app.use('/', index);
app.use('/users', users);
app.use('/test', test);
app.use('/test1', test1);
app.use('/test2', test2);

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

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

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

module.exports = app;



via Nikita M

Can't Parse Data node.js correctly

I have tried to send a post request to an api in node.js yet got the response

{ Error: 'Internal server error' }

I used this code:

var request = require('request');
var config = require("./config.json");


var request = require('request');
request.post({
  url:     'https://api.mymonero.com:8443/get_address_txs',
  json:    {method: "post", address:config.address, viewkey:config.viewkey }
}, function(error, response, body){
  console.log(body);
});

This isn't the server as I can do the exact same thing in python really easily and get the expected response

import requests
address = "*Monero Address*"
viewkey = "*Monero Viewkey*"
data = {"address":address,"view_key":viewkey}
response = requests.post("https://api.mymonero.com:8443/get_address_txs",json=data)
print(response.text)

I'm sorry if i'm being dumb I'm new to node.js

Expected Response:

{
  "total_received": "0",
  "scanned_height": 2586375,
  "scanned_block_height": 1319524,
  "start_height": 2586052,
  "transaction_height": 2586375,
  "blockchain_height": 1319524
}

Thanks :)



via Joss Bird

How to add Redis configuration in express-request-proxy node package

I'm using "express-request-proxy" node package for adding proxy for the HTTP requests. I have enabled the Redis cache which works fine in my local server.

Here is how I am loading the Redis packages in my local as suggested in the documentation (https://github.com/4front/express-request-proxy#caching):

var redis = require('redis');
require('redis-streams')(redis);

However when I'm pushing the app to cloud, I'm seeing the following error:

Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379

I have the Redis server details of the cloud but I'm not quite sure how to configure the host, port and password here.

Could someone suggest on this please?



via Ansuman