Sunday, 19 March 2017

Node.js/AngularJS: Shrink image files to specific file size

Using a MEAN environment, I would like to automatically shrink image files (.gif/.png/.jpg) which are uploaded by websites users, to a specific file size (e.g. 2 MB). Is there any node.js module available, enabling me to use something like this:

SomeModule.shrinkImage('MyHugeImage.jpg','2MB')
.then()
[...]

Haven't found anything suitable yet. May happen on client (using AngularJS) or server-side (Node.js module), I don't care. Suggestions?



via Igor P.

Getting a database does not exist error for a database that exists

I am trying to connect node with mysql. I have created the code for the connection and using phpmyadmin created a database called sampleDB. When I try to connect I get an Error: ER_BAD_DB_ERROR: Unknown database 'sampledb'. But I have created the database.

Here is my code

var express = require('express');
var mysql = require('mysql');
var app = express()

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

connection.connect(function(error){
    if(!!error){
        console.log(error);
    } else {
        console.log('Connected')
    }
})

app.get('/', function(req, resp){
    connection.query("Select * from mySampleTable", function(error, rows, fields){
        if(!!error){
            console.log('Error in query')
        }else {
            console.log('Success');
        }
    });
})

app.listen(1337);

Here is an image of of the db I created call sampleDB. enter image description here

So if I created the db called sampleDB, why am I getting an error that the sampledb table does not exist?



via Aaron

Gulp task finishing too early

I am struggling with my gulp script exiting too early.

I narrowed down the problem to this:

var gulp = require("gulp");
var through = require("through2");

function Transform() {
    return through.obj(function(file,enc,next) {
        // not calling next(null,file)
    });
}

gulp.task("test",function() {
    return gulp.src("foo")
        .pipe(Transform())
        .pipe(gulp.dest("tmp"));
});

Running gulp test, i would expect gulp never to exit since the stream should be blocked in the Transform operation that never pass the file down. But it returns.

There is obviously something i missed. What is it ?



via Blue4Whale

Understing loops with node

In node js i have a function that iterates trough an array to fill another element. Some times some proprerties are undefined, how can that be? For example i get "cannot read property formattedPrice of undefined". What is wrong with a for loop on node?

for (var i = 0; i < 10; i++) {
    //console.log(JSON.stringify(item.SmallImage));
        message.attachment.payload.elements[i] = {
            "title":items[i].ItemAttributes.Title,
            "image_url": items[i].LargeImage.URL,
            "subtitle":items[i].ItemAttributes.ListPrice.FormattedPrice,
            "default_action": {
            "type": "web_url",
            "url": "https://www.google.it",
            "messenger_extensions": true,
            "webview_height_ratio": "tall",
            "fallback_url": "https://www.google.it"
            },
            "buttons":[
                {
                  "type":"web_url",
                  "url":"https://www.google.it",
                  "title":"View Website"
              },{
                  "type":"postback",
                  "title":"Start Chatting",
                  "payload":"DEVELOPER_DEFINED_PAYLOAD"
              }             
          ]      
        }
    //sendMessage( senderId, {text: item.ItemAttributes.Title+" PREZZO**:"+item.ItemAttributes.ListPrice.FormattedPrice});
    }



via Pjotr Raskolnikov

How to setup gulp-watch with gulp-connect livereload?

Most questions and answers on this site do not contain an easy-to follow general approach to using these two libraries together.

So, being that we use the gulp-connect npm package, and we want to make use of the gulp-watch npm package, how do we set it up so that we can:

  • watch changes in some files
  • perform some operation, like building / compiling those files
  • live-reload the server once the building is done


via Alpha

Node.js - generate ugly class names

Is there a way to generate ugly class names? I mean if there's a plugin that I could use to replace .top-header class with .a9ev in my css. Also, would be great if class name in my html was also changed

How big sites like facebook or google do this?



via delco

Accessing nested object in nested array using a variable (MongoDB, Node, Inc)

I am aware of the myriad of related topics to this question but none seem to answer my problem. It is related to Node and Mongo but I think this is a general Javascript issue.

In MongoDB I need to access the options array with a variable giving the index number and then increment it's votes property. An example would be:

{
    "_id": {
        "$oid": "58ce7c6c39aff90a7c66b0d4"
    },
    "question": "Test",
    "options": [
        {
            "answer": "answer1",
            "option": "Bob Dylan",
            "votes": 2
        },
        {
            "answer": "answer2",
            "option": "Bob Geldof",
            "votes": 0
        }
    ]
}

I then get the index of the array I need to update like so:

var votedFor = "answer2";
votedFor = votedFor.match(/\d+/)[0];
var index = parseInt(votedFor) - 1;

Which I then assume the path to the integer to increment would be:

var inc = {};
inc["options[" + index + "].votes"] = 1;

Which I would like to pass in like so:

db.collection('questions')
.findOneAndUpdate({"_id": questionId}, {$inc : inc }, (err, result) => {
  if (err) return res.send(err)
  res.send(result)
})

Which updates the db like so:

    {
        "_id": {
            "$oid": "58ce7c6c39aff90a7c66b0d4"
        },
        "question": "Test",
        "options": [
            {
                "answer": "answer1",
                "option": "Bob Dylan",
                "votes": 2
            },
            {
                "answer": "answer2",
                "option": "Bob Geldof",
                "votes": 0
            }
    ],
    "options[1]": {
        "votes": 1
    }
}

Which, as you can see, as opposed to incrementing options[1].votes it has created a new property instead.

Is there any way of accessing the array index with a variable like this?



via swhizzle