samedi 28 février 2015

node mongoose connection error

data gets submitted to the database, but instead of listing the new data everything just shuts down with net::ERR_CONNECTION_REFUSED



app.post('/api/todos', function(req, res) {
todo.create({
text : req.body.text,
done : true
}, function(err, todo) {
if (err) res.send(err);
todo.find(function(err, todos){
if(err)
res.send(err)
res.json(todos);
});
});
});


Data gets submitted to db, so that confuses me even more.


Mongoose and mongoDB - duplicate key error

I'm trying to use MongoDB and mongoose for my little conversation app in where each user is having it's own collection but I'm getting an error when saving a new conversation:


ERROR: MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: chat.privatemessages.$id dup key: { : ObjectId('54f1a39ff467833f7e794636') }


My Schema:



var chatPrivateMessagesSchema = mongoose.Schema({
user: String,
with:[{
conversation_with: String,
messages:[{
text:String,
created: {type: Date, default: Date.now}
}]
}]
});

var PrivateMessages = mongoose.model('PrivateMessages', chatPrivateMessagesSchema);


Method for saving new conversation:



socket.on ('chat', function (from, to, message, callback) {
PrivateMessages.find ({}, function (err, users) {
if (err) throw err;
for (var i = 0; i < users.length; i++) {
if (users[i].user == from) {
var newPrivateMsg = new PrivateMessages ({_id: users[i]._id}, {
with: [{
conversation_with: to, //if conversation with "to" user does not exist create a new entry
messages: [{
text: message, //append a new message
created: {type: Date, default: Date.now}
}]
}]
});
newPrivateMsg.save (function (err) {
if (err) throw err;
});
}
}
});
});


So basically the output I'm looking for should be something like this?



{
"_id": "some id",
"user": "John",
"with": [{
"conversation_with": "Maria",
"_id": "some id",
"messages": [{
"text": "Hellomyfisrtmessage",
"created": "somedate"
}, {
"text": "Secondmessage ",
"created": "somedate"
}, {
"text": "Thirdmessage",
"created": "somedate"
}, ]
}, {
"conversation_with": "Peter",
"_id": "some id",
"messages": [{
"text": "Hellomyfisrtmessage",
"created": "somedate"
}, {
"text": "Secondmessage ",
"created": "somedate"
}, {
"text": "Third message",
"created": "some date"
},

]
}],

}


I'm really struggling how to insert a new entry :( Can anyone help please?


Node express GET route fails every other request when wildcard match

I have a router setup to accept any GET request that doesn't match the word "API" in it. This is for my single page app so that any bookmarked urls my javascript can't use its routes for.


The problem is every other time I refresh the page with a test url it fails.


URL: http://localhost:3000/my-test-url


First time hitting url, my index page loads.


Second time refreshing the page, error.


Cannot GET /my-test-url


Third time hitting refresh it works, and fourth time fails, and so on.



app.engine('html', cons.underscore);
app.set('view engine', 'html');
app.set('views', path.resolve(__dirname, '../client'));

// serve static content for the app from the "client" directory in the application directory
//express.static(path.join(__dirname, '../client')))
app.get(/^(?!.*\bapi\b).*$/ig, function(req, res) {
res.render('index');
});

app.listen(app.get('port'), function() {
console.log('Server up: http://localhost:' + app.get('port'));
});


Is there something that keeps the request open after it works the first time? The network tab in the browser shows the same URL each time but alternating with 404 error. Any suggestions are appreciated.


how to use match() in node.js MySQL

Using numtel:mysql for meteor which is node-mysql for meteor. How should a SQL match against query look.


Obtain some column data from influxdb to make a sum and save it again

I'm trying to obtain a value from a column call 'count', and increment the value, then save it again with other information, i have something like this in influx:



var qCount = 'select max(count) from ' + config.name +
' where itemType = \'' + config.data.item + '\'';

db.query(qCount);
count += 1;


When i obtain the value i want to increase it in in one value like, count + 1 and save it to the database.


Is it posible?


Thanks


Error installing node-sass on io.js 1.4.1 on Yosemite

I have a fresh install of io.js 1.4.1 on Yosemite via NVM. When I try to install node-sass, I get this error:



$ npm install node-sass
/
> node-sass@2.0.1 install /Users/Chris/code/<projectname>/node_modules/node-sass
> node scripts/install.js

Can not download file from http://ift.tt/1AhHaCN

> node-sass@2.0.1 postinstall /Users/Chris/code/<projectname>/node_modules/node-sass
> node scripts/build.js

module.js:322
throw err;
^
Error: Cannot find module '/Users/Chris/code/<projectname>/node_modules/node-sass/node_modules/pangyp/bin/node-gyp'
at Function.Module._resolveFilename (module.js:320:15)
at Function.Module._load (module.js:262:25)
at Function.Module.runMain (module.js:485:10)
at startup (node.js:112:16)
at node.js:863:3
Build failed
node-sass@2.0.1 node_modules/node-sass
├── get-stdin@4.0.1
├── object-assign@2.0.0
├── replace-ext@0.0.1
├── nan@1.6.2
├── semver@4.3.1
├── shelljs@0.3.0
├── cross-spawn@0.2.6 (lru-cache@2.5.0)
├── mkdirp@0.5.0 (minimist@0.0.8)
├── chalk@0.5.1 (ansi-styles@1.1.0, escape-string-regexp@1.0.3, supports-color@0.2.0, strip-ansi@0.3.0, has-ansi@0.1.0)
├── meow@3.1.0 (minimist@1.1.0, camelcase-keys@1.0.0, indent-string@1.2.1)
├── npmconf@2.1.1 (uid-number@0.0.5, inherits@2.0.1, osenv@0.1.0, ini@1.3.3, once@1.3.1, config-chain@1.1.8, nopt@3.0.1)
├── sass-graph@1.0.3 (commander@2.6.0, lodash@2.4.1)
├── gaze@0.5.1 (globule@0.1.0)
├── mocha@2.1.0 (escape-string-regexp@1.0.2, diff@1.0.8, growl@1.8.1, commander@2.3.0, debug@2.0.0, glob@3.2.3, jade@0.26.3)
└── request@2.53.0 (caseless@0.9.0, json-stringify-safe@5.0.0, forever-agent@0.5.2, aws-sign2@0.5.0, stringstream@0.0.4, oauth-sign@0.6.0, tunnel-agent@0.4.0, isstream@0.1.1, node-uuid@1.4.2, qs@2.3.3, combined-stream@0.0.7, form-data@0.2.0, mime-types@2.0.9, http-signature@0.10.1, tough-cookie@0.12.1, bl@0.9.4, hawk@2.3.1)


Is there something I'm doing wrong, or is this a bug? Thanks.


nodejs openshift cartridge - not reading custom environment variables

I am identifying my openshift nodejs app environment through system environment variables Ex: 'staging', 'production'. My custom environment variable name is OPENSHIFT_APP_ENV. I have set this in .bash_profile and ran source .bash_profile.


When I did printenv or echo $OPENSHIFT_APP_ENV in command line in my openshift app, I can see the values set properly.


But these variables are not read/set in my nodejs app. I am simply trying to read it as global.ENV = process.env.OPENSHIFT_APP_ENV || "development";


I feel that it should be simple setting issue, but could not get this working somehow. Any help will be appreciated.


How to bundle node modules with native addons using webpack in node-webkit?

I'm trying to build pty.js for use in node-webkit (i.e. nw.js) v0.8.6:



mkdir testapp && cd testapp
nvm use 0.10.36
npm install -g nw-gyp
npm install pty.js
cd node_modules/pty.js

# Build the native addon for node-webkit v0.8.6:
nw-gyp configure --target=0.8.6 && nw-gyp build


The output ends with gyp info ok .


With a simple app.js and index.html, the app launches with no errors in the JavaScript console:



<!-- index.html -->

<!DOCTYPE html>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<script src="app.js"></script>
</body>
</html>



// app.js

var pty = require('pty.js');

var term = pty.spawn('bash', [], {
name: 'xterm-color',
cols: 80,
rows: 30,
cwd: process.env.HOME,
env: process.env
});

term.on('data', function(data) {
console.log(data);
});

term.write('ls\r');
term.resize(100, 40);
term.write('ls /\r');

console.log(term.process);


package.json:



{
"name": "testapp",
"main": "index.html"
}




I want to support ES6 and JSX compilation via webpack by bundling app.js into bundle.js:



<!-- index.html -->

<!DOCTYPE html>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<script src="bundle.js"></script>
</body>
</html>


Bundling app.js:



npm install -g webpack
webpack app.js bundle.js --target="node-webkit" # This fails


But webpack fails with this error:



Hash: 6c3cd8b4ec249ab8fd05
Version: webpack 1.6.0
Time: 76ms
Asset Size Chunks Chunk Names
bundle.js 21244 0 [emitted] main
[0] ./app.js 311 {0} [built]
+ 10 hidden modules

ERROR in ./~/http://ift.tt/1BIOzSX
Module parse failed: /Users/Spencer/Desktop/testapp/node_modules/http://ift.tt/1BIOzSX Line 1: Unexpected token ILLEGAL
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
@ ./~/pty.js/lib/pty.js 10:10-46


Do I need to use a loader when requireing native binaries (like pty.node)? The webpack documentation says that the "node-webkit" target "supports native node.js modules"; perhaps it doesn't yet support native addons?


how to use Wildcards in koa-route


var path = require('path')
var route= require('koa-route');//路由
app.use(route.get('/api/*',api.before));


I can't use it for this,how should I use wildcards in koa-route? Or,which other can do ?



How to select rows[0] while inserting in node-mysql?

I'm fairly new to nodejs and callbacks. Here is my problem, using passportJS's LocalStrategy and node-mysql :



exports.register = new LocalStrategy(strategyOptionsRegister, function(req, username, password, done) {

//get data from the request
var data = {
username: username,
email: req.body.email,
password: password
};
console.log('data : ', data);

//Hash passwords
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);

bcrypt.hash(password, salt, null, function(err, hash) {
// Store hash in your password DB.
if (err) return next(err);

data.password = hash;

//insertion
connection.query('INSERT INTO USERS SET ?', data, function(err, rows) {
if (err) {
console.log(err);
return next("Mysql error, check your query");
}
return done(null, rows[0]);
});
});
});
});


I'm trying to return rows[0] containing all the data, but i don't know how should i implement the SELECT command ? Is it before or after the callback for the insertion ? For the moment, rows[0] is naturally undefined.


nodejs/jade/express in mvc: cannot get stylus to compile files

I was following this tutorial to set up proper MVC project with node.js, Express and Jade. It works great. I just have a problem with setting up Stylus and nib.


My filesystem:



/
| app
| controllers
| index.server.controller.js
| models
| routes
| index.server.routes.js
| views
| stylesheets
| style.styl
| index.jade
| config
| env
| config.js
| express.js
| node_modules
| ...
| public
| images
| scripts
| stylesheets
| style1.css
| package.json
| server.js


server.js:



var port = 8888
var express = require('./config/express')

var app = express()

app.listen(port)

console.log('server is running on port: ' + port)


express.js:



var express = require('express')
var stylus = require('stylus')
var nib = require('nib')

module.exports = function() {
var app = express()

app.set('views', './app/views')
app.set('view engine', 'jade')

require('../app/routes/index.server.routes.js')(app)

app.use(stylus.middleware({
src: __dirname + '/app/views',
dest: __dirname + '/public'
}))

app.use(express.static('./public'))

return app
}


index.server.routes.js:



module.exports = function(app) {
var index = require('../controllers/index.server.controller')

app.get('/', index.render)
}


index.server.controller.js:



exports.render = function(req, res) {
res.render('index', {
title: 'hello world',
header: 'hi tahr'
})
}


I know I don't even try to run nib here, it won't even compile .styl file. I tried thousands of different ways to actually add this middleware. I tried to add it before and after routers, statics etc.


Other files that might be relevant:



  • style1.css is just some random .css file to check if they are even loaded properly. Jade will load it fine.

  • config.js is empty.


As far as I understand it works like this: server.js asks express.js to initialize and configure itself and waits to get a finished express object.


Express asks for routers the index.server.routers.js file which in turn asks index.server.controller.js to do some stuff. It does its stuff, after it completes express.js can return app to server.js where it will start to listen on port 8888.


I know it might have something to do with the order in which I order my files, maybe because I render too soon or something... but those .styl files still should appear! Using debug: true won't show anything in the console and the only message there is "server is running on port: 8888".


Firefox developer tools are saying that style1.css loads properly while the query for style.css fails with 404 (since there is no such filed compiled by Stylus).


After hours (literally) spent I give up and ask for your help, stackoverflowers.


Emacs M-x term can't find node/coffee

I've been plonking around on mac-emacs, and I've M-x install-package-d coffee-mode. I decided to try out the coffee-compile-file command, but when I ran it, it failed, complaining that it couldn't find the coffee command.


So, I open up terminal, on ZSH and Bash. coffee and node run fine on both. So, split my emacs screen, plink out M-x term, let bash load, and type coffee:



bash-3.2$ coffee
bash: coffee: command not found


Odd. I tried the same for node and npm.



bash-3.2$ node
bash: node: command not found
bash-3.2$ npm
bash: npm: command not found


My question is, why does this happen only on M-x term, and how can I fix it.


Passport.JS doesn't working (AngularJS + NodeJS + MySQL + Redis Store for session datas)

I'm trying to use PassportJS to authenticate requests on my site, but it's not working. When I trying to login nothing happening. I'm using MYSQL database to store the user datas and I didn't find a tutorial for this.


APP.JS:



var session = require('express-session');
var routes = require('./routes');
var sha1 = require('sha1');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var flash = require('connect-flash');
var RedisStore = require('connect-redis')(session);
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));

app.use(session({
store: new RedisStore({
host: '127.0.0.1',
port: 6379,
prefix: 'sess'
}),
resave: true,
saveUninitialized: true,
secret: 'xxxxxxx'
}));

app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},

function(username, password, done){

var connection = mysql.createConnection(
{
host : sql.host,
user : sql.user,
password : sql.password,
database : sql.db_users
}

);

console.log(username);
console.log(password);

connection.connect();

var queryUserCheck = 'SELECT userID, email, password, users WHERE email = "' + username + '"';

connection.query(queryUserCheck, function(err, rows, field) {
if(err){
res.status(500).end(err);
console.log(err);
connection.end();

}else{

user = rows[0];
userID = rows[0].userID;
console.log('Checkpoint 1');

if(!user) { return done(null, false, {message: 'The user is not exist'});}
else if(sha1(password) != user.password) { return done(null, false, {message: "Wrong password"});}
else{
console.log('Checkpoint 2');
return done(null, user);}
connection.end();
}
});
}
));

passport.serializeUser(function(user, done) {
console.log('serializeUser');
done(null, user.id);
});

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

routes.init(app, passport);


I'm actually not really understand the above 2 function. I know it's need to attach and deattach the user from the session, but do I need to change anything on these functions to make it customized or just leave as is?


Router:



exports.init = function(app, passport){

app.post('/login', login);
app.get('/logout', logout);
app.get('/userinfo', checkAuth, require('./users/users/userDetails'));


function login(req, res, next){

passport.authenticate('local-login', function(err, user, info){
if(err){
return next(err);
}

console.log('Authentication is successfull');

});
}

function logout(req, res){

if(req.isAuthenticated()){

req.logout();
req.session.messages = "Log out successfully";

}

res.writeHead(200, { 'Content-Type': 'application/json'});
res.end(true);

}

function checkAuth(req, res, next){

if(req.isAuthenticated) return next();
else{
res.status(401).end("Not Authorized!");
}
}

};


Could somebody help me what I missed? Thank you so much.


paypal node.js API malformed request

I'm creating an array for the items field in the JSON doc required to create a paypal payment.


I can create the payment with dummy data, all looks good. However when I use real data via an iteration to create the object, after the .create request I get a MALFORMED_REQUEST error.


Code is:



var items = [];
for(i = 0; i < req.body.parts.length; i++)
{
part = req.body.parts[i];
items.push ({"name": part.part_display_name, "description": part.SKU, "sku": part.SKU, "price": part.price, "currency": "USD", "quantity": 1});
};
console.log (items);


Example output:



[ { name: 'Detective Handle Checker Grips',
description: 'vyctorslab_pistol_2015A_mowrer_handle_detective_checker_black-rubber-and-brass',
sku: 'vyctorslab_pistol_2015A_mowrer_handle_detective_checker_black-rubber-and-brass',
price: 50,
currency: 'USD',
quantity: 1 },
{ name: 'Detective Hammer',
description: 'vyctorslab_pistol_2015A_mowrer_hammer_detective_base_steel',
sku: 'vyctorslab_pistol_2015A_mowrer_hammer_detective_base_steel',
price: 50,
currency: 'USD',
quantity: 1 } ]


It certainly looks like the required JSON, however when creating the payment as follows:



var payment = {
"intent": "order",
"payer": {"payment_method": "paypal"},
"redirect_urls": {"return_url": return_url, "cancel_url": cancel_url},
"transactions": [
{"amount": req.body.total_price, "description": "Maykrlab model purchase.","item_list": items }
]
};


Output is:



{ intent: 'order',
payer: { payment_method: 'paypal' },
redirect_urls:
{ return_url: 'http://ift.tt/1E0AbEk',
cancel_url: 'http://ift.tt/186R2bT' },
transactions:
[ { amount: 500,
description: 'Maykrlab model purchase.',
item_list: [Object] } ] }


All still seems to be OK, the [Object] in the last line above is the items JSON created earlier.


However, the call to paypal is returned with:



{"response":{"name":"MALFORMED_REQUEST","message":"Incoming JSON request does not map to API request","information_link"
:"http://ift.tt/1eUIDbv","debug_id":"4f5997d207eca","httpStatusCode
":400},"httpStatusCode":400}


I believe I'm not correctly turning the items object created by the iteration into the correct format for posting to the paypal API. Can anyone advise? It's probably a case of needing to use .stringify in some place?


Using OSC with NodeJS

I need to create a test server in NodeJS that supports OSC over UDP. After a quick search there seems to be a lot of options. Can anyone recommend a module for OSC in NodeJS?


Mongoose+Node API delays db query

GET works great, DEL works great too. but POST... : What happens is that string goes in db. It does not show up(on my webapp). When I add a second string, it finally shows up. As if there is a delay?



app.post('/api/todos', function(req, res) {
todo.create({
text : req.body.text,
done : true
}, function(err, todo) {
if (err)
res.send(err);
});
todo.find(function(err, todos){
if(err)
res.send(err)
res.json(todos);
});


But if I do it with delete, it works like normal. deleted the id and show the rest of the id's.



app.delete('/api/todos/:todo_id', function(req, res){
todo.remove({
_id : req.params.todo_id,
}, function(err, todo){
if(err)
res.send(err);
});
todo.find(function(err, todos){
if(err)
res.send(err)
res.json(todos);
});
});


I hope my question makes sense, I'm not so good at english


NodeJS Bookshelf Users-Followers Relation Sample

I'm trying to create a Users-Followers Relationship with Bookshelf but I can't achieve it :(


Could you ilustrate me with a simple sample?


Thanks for your time :)


StrongLoop deployment

I want to install a service in AWS as below command since i have two apps needs to be hosted in the same server. I am able to deploy an app in the default service strong-pm. But when i try to create a new service as below


sudo slc pm-install --upstart 0.6 --user manhunt-pm --port 6666 --job-file /etc/init/manhunt-pm.conf


The service gets started. But when i try to deploy the tar file, I am getting the following error


Deploy /home/ec2-user/manhunt-0.0.0.tgz to http://localhost:6666 failed: read ECONNRESET


From the aws log, i see the following message



Feb 27 05:50:05 ip-172-31-28-147 strong-pm: TypeError: Object #<Object> has no method 'sendError'</b>
Feb 27 05:50:05 ip-172-31-28-147 strong-pm: at /usr/lib/node_modules/strongloop/node_modules/strong-pm/lib/pack-receiver.js:94:12
Feb 27 05:50:05 ip-172-31-28-147 strong-pm: at /usr/lib/node_modules/strongloop/node_modules/mkdirp/index.js:46:53
Feb 27 05:50:05 ip-172-31-28-147 strong-pm: at Object.oncomplete (fs.js:107:15)
Feb 27 05:50:05 ip-172-31-28-147 strong-pm:
Feb 27 05:50:05 ip-172-31-28-147 init: manhunt-pm main process (13087) terminated with status 8
Feb 27 05:50:05 ip-172-31-28-147 init: manhunt-pm main process ended, respawning
Feb 27 05:50:05 ip-172-31-28-147 su: (to manhunt-pm) root on none
Feb 27 05:50:10 ip-172-31-28-147 strong-pm: sl-pm.js: control listening on path `/var/lib/manhunt-pm/pmctl`
Feb 27 05:50:10 ip-172-31-28-147 strong-pm: sl-pm.js: listen on 6666, work base is `/var/lib/manhunt-pm/.strong-pm` with config `/var/lib/manhunt-pm/.strong-pm/config`


Am I missing something? Or is there any other way that I want to host two different apps in the same server in different port say 3000 and 3001. Please help.


Module version mismatch with headless browser and desktop Node

I'm getting a "Module version mismatch error" when I try to use a headless browser with a desktop Node shell. I've tried Zombiejs and Phantomjs with both nw.js and atom-shell; in both cases as soon as the headless browser comes into play the application crashes with a module mismatch error.


Here's the error with Phantomjs and atom-shell:



Uncaught Exception:
Error: Module version mismatch. Expected 41, got 14.
at Error (native)
at Object.module.(anonymous function) (ATOM_SHELL_ASAR.js:118:20)
at Object.module.(anonymous function) [as .node] (ATOM_SHELL_ASAR.js:118:20)
at Module.load (module.js:370:32)
at Function.Module._load (module.js:325:12)
at Module.require (module.js:380:17)
at require (module.js:399:17)
at bindings (/Users/Ajay/Projects/atom-shell/node_modules/phantom/node_modules/dnode/node_modules/weak/node_modules/bindings/bindings.js:76:44)
at Object.<anonymous> (/Users/Ajay/Projects/atom-shell/node_modules/phantom/node_modules/dnode/node_modules/weak/lib/weak.js:7:35)
at Module._compile (module.js:475:26)


Any idea what's causing the error?


Replacement for jsdom in Node.js

jsdom 4 has discontinued support for Node.js.


From the documentation:



Note that as of our 4.0.0 release, jsdom no longer works with Node.js™, and instead requires io.js. You are still welcome to install a release in the 3.x series if you are stuck on legacy technology like Node.js™.



(I've heard about the criticism around Joyent's management of Node.js, but the "legacy technology" here sounds a bit derogatory.)


While jsdom 3.1.2 still works fine, I would like to build new projects on a library that receives regular updates and supports Node.js. Is anybody aware of an alternative project that is still maintained by its authors?


Twitter Search API and my website

I have been using Node.js to create a simple endpoint that hits Twitter's Search API and returns me results.


Then, to display those results, I have been using twttr.widgets.createTweet() and appending each result to a container.


However, when I do this, only about ten of the results are displayed, and the rest exist in the div as hidden. Is there a way for me to create a simple feed of dynamic search results?


Sending delayed emails with node-mailer on Heroku

I have a MEAN stack web app being hosted on Heroku. I'm using node-mailer (http://ift.tt/Hgzl9A) to send emails when people create a form, sign up for a form, and a few other things.


Ideally, I would like to send a reminder email one week prior to the date specified on the form.


I have no idea how to accomplish this with node-mailer, and have been scouring google looking for a solution, but come up short.


Is there a good way to send delayed emails with node-mailer? I don't want to switch mailing services if I can avoid it.


Thanks in advance.


How to spawn new process everytime I call a recursive function in Node.js

I am new to node.I am trying to create a recursive function say Merge Sort.I want to create a new process every time I call the function.


Basically I want to divide the task into two parts every time I call the function and pass each part to a new process.


Here is my code: merge.js



process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
var arr = chunk.trim().split(' ');

mergeSort(arr,0,arr.length - 1);
// I want to create new threads like this
// CreateNewLeftThread
// CreateNewRightThread
// Join(lefThread.rightThread)


function mergeSort(arr,left,right) {

if (left < right) {

var mid = Math.floor(left + (right - left)/2);
mergeSort(arr,left,mid);
mergeSort(arr,mid+1,right);
merge(arr,left,right,mid);

}

}

function Merge(Parameters) {

/*Code Here*/

}

process.exit(0);

});

Titanium Studio wont load any emulators, returns errors upon starting

I have recently installed Titanium Studio. Upon opening the program i get the error



"An internal error occurred during: "Computing SDK Info...".
java.lang.NullPointerException"


If i attempt to create a new emulator i get the error:



"An internal error occurred during: "Refreshing provisioning information...".
java.lang.NullPointerException"


Ive seen this question a million times but I cant get anything to work. I uninstalled and reinstalled node. I heard Titanium Studio wasnt working with node v12 so i went back to 0.10. I uninstalled and reinstalled java i reinstalled the java sdk i re installed the android sdk, i have attempted to "sudo npm install titanium -g" about 50 times and it always returns



Users/admin/.nvm/v0.10.36/bin/ti -> /Users/admin/.nvm/v0.10.36/lib/node_modules/titanium/bin/titanium
/Users/admin/.nvm/v0.10.36/bin/titanium -> /Users/admin/.nvm/v0.10.36/lib/node_modules/titanium/bin/titanium
titanium@3.4.1 /Users/admin/.nvm/v0.10.36/lib/node_modules/titanium
├── sprintf@0.1.5
├── colors@0.6.2
├── longjohn@0.2.4
├── humanize@0.0.9
├── async@0.2.10
├── wrench@1.5.8
├── semver@2.2.1
├── fields@0.1.23 (keypress@0.2.1)
├── optimist@0.6.1 (wordwrap@0.0.2, minimist@0.0.10)
├── temp@0.6.0 (osenv@0.0.3, rimraf@2.1.4)
├── winston@0.6.2 (cycle@1.0.3, stack-trace@0.0.9, eyes@0.1.8, pkginfo@0.2.3, async@0.1.22, request@2.9.203)
├── request@2.27.0 (json-stringify-safe@5.0.0, aws-sign@0.3.0, forever-agent@0.5.2, qs@0.6.6, tunnel-agent@0.3.0, oauth-sign@0.3.0, cookie-jar@0.3.0, mime@1.2.11, node-uuid@1.4.2, form-data@0.1.4, hawk@1.0.0, http-signature@0.10.1)
├── moment@2.4.0
├── jade@0.35.0 (character-parser@1.2.0, commander@2.0.0, mkdirp@0.3.5, with@1.1.1, transformers@2.1.0, constantinople@1.0.2, monocle@1.1.50)
└── node-appc@0.2.14 (diff@1.0.8, node-uuid@1.4.2, xmldom@0.1.19, semver@2.1.0, adm-zip@0.4.7, dox@0.4.6, uglify-js@2.3.6)


running "ti info" returns



|[ERROR] Failed to run command "info"
/usr/local/lib/node_modules/titanium/node_modules/longjohn/dist/longjohn.js:185
throw e;
^
logger.log (/usr/local/lib/node_modules/titanium/lib/logger.js:72:21),target. (anonymous function) [as error] (/usr/local/lib/node_modules/titanium/node_modules/winston/lib/winston/common.js:4 5:21),CLI.<anonymous> (/usr/local/lib/node_modules/titanium/lib/cli.js:955:17),/usr/local/lib/node_modul es/titanium/node_modules/async/lib/async.js:119:25,Object.<anonymous> (/usr/local/lib/node_modules/titanium/node_modules/async/lib/async.js:24:16),CLI._ fireHookCallback (/usr/local/lib/node_modules/titanium/lib/hook.js:269:12),/usr/local/lib/node_modu les/titanium/lib/hook.js:248:10,/usr/local/lib/node_modules/titanium/node_modules/ async/lib/async.js:232:13,async.eachSeries (/usr/local/lib/node_modules/titanium/node_modules/async/lib/async.js:130:20)"


and "check" ing titanium in setup gives me this information:



Check Environment
Node.js
✓ node up-to-date (v0.12.0)
★ npm new version v2.6.1 available! (currently v2.5.1)

Titanium CLI
✓ cli up-to-date (v3.4.1)

Titanium CLI Dependencies
✓ async up-to-date (v0.2.10)
✓ colors up-to-date (v0.6.2)
✓ fields up-to-date (v0.1.23)
✓ humanize up-to-date (v0.0.9)
✓ jade up-to-date (v0.35.0)
✓ longjohn up-to-date (v0.2.4)
✓ moment up-to-date (v2.4.0)
✓ node-appc up-to-date (v0.2.14)
✓ optimist up-to-date (v0.6.1)
✓ request up-to-date (v2.27.0)
✓ semver up-to-date (v2.2.1)
✓ sprintf up-to-date (v0.1.5)
✓ temp up-to-date (v0.6.0)
✓ winston up-to-date (v0.6.2)
✓ wrench up-to-date (v1.5.8)

Titanium SDK
✓ latest sdk installed (v3.5.0.GA)
✕ selected sdk selected Titanium SDK "vundefined" is not installed

Mac OS X Environment
✓ CLI Tools installed

iOS Environment
✓ Xcode installed (6.1.1)
✓ iOS SDK installed (8.1)
✓ WWDR cert installed
! developer cert not found
! distribution cert not found
! dev provisioning not found
! dist provisioning not found

Android Environment
! sdk Android SDK not found
! targets no targets found
! avds no avds found
✓ ndk installed (undefined)
✓ ndk-build installed (undefined)

Java Development Kit
✕ jdk JDK not found!

Intel® Hardware Accelerated Execution Manager (HAXM)
✓ compatible
✓ installed

Network
✓ online
- no proxy server configured
✓ http request test
✓ https request test

Directory Permissions
✓ home directory
✓ titanium config directory
✓ titanium sdk install directory
✓ temp directory"


I have tried deleting my config.json file and letting Titanium recreate it and setting the properties in the cli but absolutely nothing changes these errors. I am really at my wits end here. I really really need some kind of help so if anybody please knows how to just make Titanium Studio work I would be so grateful, Ive been trying for days...


Parsing Node Command Line Arguments

I am learning how to use node.js, but am having trouble parsing command-line arguments. The following line:



node test.js --input=in.txt


Gives a parsing error when the code reaches this command:



var fileName = JSONparse.(process.argv[2]);


Results in the error:



undefined
--input=in.txt

Syntax error: Unexpected number


What I am trying to do is create an optional variable for the input file. If it is not specified in the command-line, it should resolve to 'a.txt'.


I have not found an easy way of creating default parameters, or use identifiers such as '--input=' to not have to worry about the order in which arguments are passed (I know it does not matter in this case with one argument).


Running Protractor from Node-webkit

Is is possible to run Protractor in any other way except using CLI?


Is there an API call which will simulate the command: 'protractor config file.js'?


I would like to start a test through a node-webkit application, and even though I can connect directly to the ChromeDriver through the directConnect parameter, this is no use if I can't run protractor from inside the script.


Of course, this is in an environment where Node and Protractor aren't available from CLI... simulating a distribution environment where the user doesn't have to install additional apps apart from my node-webkit (hence the node-webkit usage).


Thank you in advance for any pointers!


How to export inter-depended Node.js functions efficiently

I have a Node.js module containing numerous functions:


myfuncs.js:



var foo = function(d) { return d + 1 })
var bar = function(d) { return foo(d) + 2 }
var baz = function(d) { return foo(d) + bar(d) + 3 })


I'd like to export all of these function in myfuncs.js for use in another module. What is the best way to accomplish this? Since some of the functions are used in other functions; for example foo is used in bar and baz, the only way I can see to export, is to list all the exports like this, so that they are available in another module.


myfuncs.js:



var foo = function(d) { return d + 1 })
var bar = function(d) { return foo(d) + 2 }
var baz = function(d) { return foo(d) + bar(d) + 3 })

module.exports.foo = foo;
module.exports.bar = bar;
module.exports.baz = baz;


My issue is that I have dozens of functions and exporting each function in this manner seems inefficient. Is there a better way to export Node functions?


Any packages for creating a dynamic restful resource API in an express server?

For example, think of something like Firebase.



  • If a user GETs from /, it will respond with the data of the entire collection (preferably automatically handle pagination if there is a lot of data)

  • If a user GETs from /some/.../endpoint, it will automatically resolve the resource at that point, no matter how deep you go, without any configuration necessary

  • If a user PUTs from /some/.../endpoint, it will automatically deposit the data at that endpoint, (creating the necessary storage structures / collections / objects for the underlying data provider)


I don't want something like mongoose, because I don't want to explicitly declare my own models. I want to keep the specifics of the application on the front-end as much as possible, so the server can have minimal configuration.


Is there any node.js library that takes care of this for you? If not, I'm sure lots of people have experience in creating dynamic REST endpoints like this. What insight can you provide?


error message for mongoose schema type mismatch

I have the following mongoose schema definition for a property amount.


If I don't pass a number or pass something less than 10, I am able to get the correct error messages as specified.


But I get a blank error message if the type specified is not number. For e.g. if I pass 'somestring'. It rightfully errors out on save, but with no message. Where can I specify the error message for type mismatch?


var ExpenseSchema = new Schema({



amount: {
type: Number,
required: 'Please fill Expense amount',
min: [10, 'Please enter at least 10'],
....

node.js command line tool

I am writing my very first command line tool with node.js. I'm familiar with the concept of async io and understand the benefits of using it. I am wondering however, since this tool will do the following:



  1. Perform some FS operations (e.g. create folder, write to some files)

  2. Make a network request (e.g. download some stuff into this folder)

  3. Produce a result (meaning a bunch of files)

  4. Exit


Should I really be using all the async versions for these methods? for instance mkdirp() is also available as mkdirpSync() (from the fs-extra module), so the real question is:



Why do I even have to bother using async functions in a program that is due to terminate upon completion? and has no real impact in case the application thread is blocked?



Thanks.


Best practices to invalidate JWT while changing passwords and logout in node.js?

I would like to know the best practices to invalidate JWT without hitting db while changing password/logout.


I have the idea below to handle above 2 cases by hitting the user database.


1.Incase of password changes, I check for password(hashed) stored in the user db.


2.Incase of logout, I save last-logout time in user db, hence by comparing the token created time and logout time, I can able to invalidate this case.


But these 2 cases comes at the cost of hitting user db everytime when the user hits the api. Any best practise is appreciated.


MKDIRP does have a permission to create new folder, how to give the permission?

I installed mkdirp to create new folder when the folder is not existed.


(Using npm install -g mkdirp)


But it seems like the mkdirp doesn't have the permission to create new folder,


when I try, I got this error,



{ [Error: EACCES, mkdir '/upload'] errno: 3, code: 'EACCES', path: '/upload' }


This is my code, and I'm using MAC



'fileUpload' : function(req, res, next){
var mkdirp = require('mkdirp');
mkdirp('/upload/image', function (err) {
if (err) console.error(err)
console.log ('!');
});


How can I give the permisson to mkdirp to create new folder?


How to set connection charset using node-oracledb

I am trying to connect to Oracle database from node.js.


I have successfully installed the node-oracledb driver. I can connect to my Oracle database using the TNSNAMES file.


The problem is, my database is using NLS_CHARACTERSET EE8ISO8859P2 character set. In php applications I can change that to use UTF-8 while calling oci_pconnect.


Is there a way to do the same with node driver?


find by date in mongoose

I have a doubt, I have save some dates like this, timeStamp: "2014-10-30T15:13:37.199Z", in mongoose.


But I want to make a search like this:



model.find({ timeStamp: { $gte: startDate, $lt: endDate }})


Where startDate and endDate are for example 2014-10-30. Is that possible.


why I cannot use socket.io module if install globally

I just want to ask why I cannot use the module of socket.io if I install this globally, I am new in socket.io, I tried to execute this command "node install socket.io" to this C:\Users\username>node install socket.io but then after It installed and run my app.js.I get error cannot find socket.io module..but when I run command "node install socket.io" where my app.js is located it works fine.


Thank you in advance.


findOneAndUpdate - Update the first object in array that has specific attribute

I have an object that has attributes. This includes an array of other Objects that have their own attributes.



Lobby:
--> "a": "b"
--> "c": "d"
--> Players:[
--> 0
--> "x": "23"
--> "status": "ready"
--> 1
--> "x": "54"
--> "status": "open"
--> 2
--> "x": "16"
--> "status": "open"


How would I go about updating the first Player Object that has "status": "open" (in this case 1) to a new object?


For example:



player = {
x: "125",
status: 'joined'
};

Stylus inline SVG data uri without base64 encoding

How can I embed a SVG data uri in CSS using Stylus preprocessor without the SVG being Base64 encoded?


Like this:



background: url('data:image/svg+xml;utf8,<svg>[...]</svg>');


instead of this:



background: url('data:image/svg+xml;base64,PD94bWwg[...]');


Normaly I've used stylus.url() to embed images, but it will also Base64 encode SVGs.


I want to use data uris instead of external files to save file requests. And I've realised that Base64 encoding SVGs actually adds bytes instead of reducing size.


I can't find a method to embed the SVG as-is.


How to render a view file included a dot (.) character?

I'm trying to render a view file named cores.index.view, However, I always got Error: Cannot find module 'view'. It seems like Express interprets the dot of the file name as a file extension instead of a normal file name.



// Partials template, jade format, for angular.js
exports.views = function (req, res) {
//Get data from regex (*)
var path = req.params['0']; // path equals to cores.index.view
res.render('../../packages/' + path);
};


I tried to search about this issue, however, didn't find anything related to this topic. Any help would be appreciated.


What is the most efficient way to read only the first line of a file in Node JS?

Imagine you have many long text files, and you need to only extract data from the first line of each one (without reading any further content). What is the best way in Node JS to do it?


Thanks!


MongoDB MonkAPI setting a variable based on find result that is available outside the db request

I'm trying to set a variable based on the result of a find through Monk API on MongoDB in a Node JS application (it's my first time of using MongoDB).


This is an example of the code I have;



var variableIWantToSet;
var collection = req.db.get('myCollection');
collection.find( { foo: 'bar' },{
fields : { myTargetField: 1, _id: 0},
limit : 1,
sort : {$natural : -1}
}
, function(err, doc) {
if (err) {
console.log(err);
}
variableIWantToSet = doc[0].myTargetField;
});
console.log(variableIWantToSet);


If I console.log(doc[0].myTargetField) within the function I get the right value, but the console.log(variableIWantToSet) returns undefined.


Help appreciated. Thanks.


Sorting Mongoose populate() with a condition

I’m currently using populate() like so:


Schemas:



var DefinitionSchema = mongoose.Schema({
title: String,
slug: String,
description: String
});
DefinitionSchema.index({description: 'text'});
DefinitionSchema.plugin(textSearch);

var SectionSchema = mongoose.Schema({
heading: String,
intro: String,
alpha: false,
definitions: [{ type: Schema.Types.ObjectId, ref: 'Definition' }]
});

var PageSchema = mongoose.Schema({
time : { type : Date, default: Date.now },
title: String,
slug: String,
intro: String,
body: String,
sections: [SectionSchema]
});


Page rendering:



exports.edit = function(req, res){
Page.findOne({ slug: req.param('page') }, function(err, page){
res.render('admin/page_edit', { page: page});
})
.populate({path: 'sections.definitions', options: {sort: {slug: 'asc'}}});
};


This means that sections.definitions are sorted alphabetically for every section.


I was wondering whether it was possible to pass a condition to the sort within populate, so that I can change the sorting based on the value of (the parent document) section.alpha.


I figured it would look like this:



function sorting(section) {
var sort = {}
if (section.alpha) {
sort = {slug: 'ace'}
}
return sort;
}

query
...
.populate({path: 'sections.definitions', options: {sort: sorting(sections)}});


Any help would be much appreciated.


Thanks, Samuel


run node app with es6features

I use the require hook of BabelJS (formerly named 6to5) to run node apps with es6features:



// run.js
require("babel/register");
require("./app.js6");


I call node run.js to run my app.js6. I need to install BabelJS and provide a run.js for each project I'd like to use es6features. I would prefer a call like nodejs6 app.js6. How can I achieve this system independently (Unix and Windows)?


Best way to perform a full text search in MongoDB and Mongoose

I'm searching on Google since days and I tried many things but I still can not perform a good full text search on my user collection.


I tried ElasticSearch but was pretty impossible to query and paginate...


I tried many plugins for Mongoose like ElMongo, mongoose-full-text, Mongoosastic, etc... everyone are really bad documented and I don't know how to perform a good full text search.


So, my collection is a normal collection:



user = {
name: String,
email: String,
profile: {
something: String,
somethingElse: String
}
}


I have a search input in a page with a simple POST, if I type hello world what I need is to search on the entire collection fields the matching words of my search query and get the results.


It will be really nice also to have options to handle a pagination like 10 items per page or something...


What is the best solution to achieve this? I'm using MongoDB 2.6.* with Mongoose, NodeJS and ExpressJS.


Thanks.


'or' query with different data types in sails.js

Given routes



GET /user/42
GET /user/dude


where 42 is user id and dude is username.


So, I want to have method in my controller that return user for both cases. Here it is:



// api/controllers/UserController.js
findOne: function(req, res) {
User.findOne({
or: [
{id: req.params.id},
{username: req.params.id}
]
}).exec(function(err, user) {
if (err) {
return console.log(err);
}
res.json(user);
});
},


When I try to GET /user/42 everything is fine.


When I try to GET /user/dude I get error:



Error (E_UNKNOWN) :: Encountered an unexpected error


error: invalid input syntax for integer: "dude"



It seems like sails refuses to process {id: 'dude'} because of type mismatch.


I am using sails 0.10.5 with sails-postgresql 0.10.9. So what am I doing wrong?


UPD: I do know how to solve problem. Of course I can put if statement to my controller and check what type of parameter it got. Actually, I just created two routes with regexp parameters that point to single method.


My actual problem is why I can not do this with or. Does sails provide such way?


What type of error object is retuned from a http call if statusCode is not 200?

I am making http calls in meteor using the npm 'request' package.


I would like to know what type of error object is created when a response.statusCode is not equal to 200? Is this handled by the javascript engine and considered a runtime error?


Or if the statusCode is not equal to 200 is determined by the service provider whether they will create an error object or not?


If the latter, do I create a 'manual error', new Error('throwing my own error for the catch block to handle')



var request = function() {
// HTTP call to server
},
function (error, response, body) {
if (!error && response.statusCode === 200) {
// processed and created data object
return data
}
else {
return (error) ; // How can I ensure the catch(e) block in the try/catch method will catch the error with an addition of my own 'message'.
}
})
};

try {
request()
}
catch(e) {
console.log(e)
}


For my scenario, I would like to ensure the catch(e) block will grab this error and I would like to add my own message including the stack trace.


How can I filter populated values in sails.js?

I have model User. To simplify my issue it has not attributes (except id that is produced by sails engine):



module.exports = {

}


I have also model UserPost:



module.exports = {
attributes: {
user: {
required: true,
model: 'user'
}
}
}


I want to find posts of user with id equal to 42. I have that records in database, both user with id 42, and its posts.


This doesn't work:



UserPost.find().populate('user', {
id: 42
}).exec(function(err, posts) {
res.json(posts);
});


How can I do that?


Multiple near with mongoose

I have the following "query":



MySchema
.where('address1.loc').near({
center: {
type: 'Point',
coordinates: user.address1.loc
},
maxDistance: 10 * 1000
}).where('address2.loc').near({
center: {
type: 'Point',
coordinates: user.address2.loc
},
maxDistance: 10 * 1000
})
.exec(function(err, objects) {
console.log(err);
console.log(objects);

if(err) return eachCallback(err);

return eachCallback();
});


My schema has two addresses (one pickup- and one handover-address). So I have to use two "nears". But this doesn't seem to be possible:


{ [MongoError: Can't canonicalize query: BadValue Too many geoNear expressions] name: 'MongoError' }


What are my alternatives?


Update: I talked to some guys from MongoDB. Although my use case for this is valid, this doesn't seem to be possible out-of-the-box. So I'm looking for a "workaround". If you need details about the use case, let me know.


And here is how I defined the location inside my "addresses":



...
loc: {type: [Number], index: '2dsphere'},
...

How can I make use of LOCAL VARIABLES within a heroku postgres query?

I have looked around in many MANY threads, and through various documentation however for what seems like such an incredibly SIMPLE task, this is driving me insane.


I have a node.js webapp which generates a userId upon login, and is stored within a session object.


req.user.id <== my local variable for the user id.


The code I have so far is along these lines:



var query = client.query("SELECT * FROM programs WHERE authorid = req.user.id", function (err, result) {

if (err){
//Do erranous things
} else {
// Do good things
}
});


What am I doing wrong? How can I do this simple task of comparing a database entry to a value stored in a local variable?


Any / all help appreciated - I've been trying to do this for 6 hours.


Error when installing log.io using npm

I am trying to install log.io following the instruction from http://ift.tt/Hbf34s. It suggests using npm install command.



npm install -g log.io


The error I am getting is like below. And I tried on both Mac OS and Ubuntu, both no luck. Can anyone help me?



> contextify@0.1.13 install /usr/local/lib/node_modules/http://ift.tt/1oo5iT5
> node-gyp rebuild

npm http GET http://ift.tt/Zu2vrL
npm http GET http://ift.tt/Zu2vbx
npm http 304 http://ift.tt/Zu2vbx
npm http 304 http://ift.tt/Zu2vrL
gyp: Call to 'node -e "require('nan')"' returned exit status 1. while trying to load binding.gyp
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack at ChildProcess.onCpExit (/usr/share/node-gyp/lib/configure.js:431:16)
gyp ERR! stack at ChildProcess.EventEmitter.emit (events.js:98:17)
gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:797:12)
gyp ERR! System Linux 3.13.0-32-generic
gyp ERR! command "nodejs" "/usr/bin/node-gyp" "rebuild"
gyp ERR! cwd /usr/local/lib/node_modules/http://ift.tt/1oo5iT5
gyp ERR! node -v v0.10.25
gyp ERR! node-gyp -v v0.10.10
gyp ERR! not ok
npm WARN This failure might be due to the use of legacy binary "node"
npm WARN For further explanations, please read
/usr/share/doc/nodejs/README.Debian

npm ERR! Error: ENOENT, chown '/usr/local/lib/node_modules/http://ift.tt/1vJmVmd'
npm ERR! If you need help, you may report this log at:
npm ERR! <http://ift.tt/wnQOXn;
npm ERR! or email it to:
npm ERR! <npm-@googlegroups.com>
...

Request a SQL(CQL) query to nodejs server

I want to execute a CQL query on a node.js server which can be requested from a client/browser. I send the following query:



localhost:3000/selectquery?query="select * from simplex.songs;"


I am using the following GET method to execute the request:



app.get('/selectquery',function(req,res){
var query_string = req.query.query;
console.log(query_string);
client.execute(query_string,function(err,result){
if(err){
console.log(err);
res.status(404).send(err);
}
else{
res.json(result);
}


});


});


When I make any request,I get the following error message:



{
"name": "ResponseError",
"message": "line 1:0 no viable alternative at input 'select * from simplex.songs;'",
"info": "Represents an error message from the server",
"code": 8192,
"query": "\"select * from simplex.songs;\""
}


It think, i need to parse the query_string and remove " or ' from the query. How I can do this?


vendredi 27 février 2015

How to debug assemble.io (ideally in Chrome Console)

I want to be able to capture and inspect all Objects that are being parsed by Handlebars in Assemble.io. Ideally in Google Chrome Developer Tools, just like I would inspect any other JavaScript. Any ideas?


With Facebook's EventEmitter is there a way to make a late listener receive an event thats already been emitted?

If I have an object thats fetching data and it emits a "ready" event but another object starts listening for that event after it has already been fired is there a direct way of allowing that listener to receive that missed event.


Purely hypothetical example (so please don't ask why I would do this):



var dataModule = new DataModule(); // data fetching happens here.
setTimeout( function(){
dataModule.once( 'ready', function(){
// Perform some action when the data is ready
} );
}, 5000 ); // Five second delay


In the above example lets assume that DataModule fetches it's data asynchronously and its really quick.


Wrapping multiple similar mongoose schemas into a single schema

I have a server which stores records representing Objects, and which uses Mongoose to manage these records. I want to be able to query/update/etc. all objects with a simple API (i.e. a single endpoint). Different types of Objects have some identical attributes, and some different attributes, so a single, static Object schema won't do. Instead, I still want to have a single schema, but I want to be able to change it slightly by adding/deleting fields when I create each new Object, with the fields which are/aren't present depending on the type of the Object. I don't want a mixed schema, because I want error validation for each type of Object. I want a single schema (as opposed to a different schema for each type of Object) so that I can just do



Object = mongoose.model('Object', ObjectSchema);
Object.findOne({objectType: "type1"}, function(err, model) {
...
});


So basically, I want field validation, while still maintaining some flexibility for attributes, and a single point to query/update/etc. my Object records. If I change the schema with each new Object, recompile it into a model, and create a new instance of that model, will all the instances of the different models (compiled from different modified versions of the same schema) still be queryable as above?


Obviously, I'm new to Mongoose. I just talked a lot about the schema here, and I honestly don't know whether I should have used the word "model" in place of "schema" in some places. I just don't know how I can accomplish all of this. Let me know if I make no sense.


Wrapping multiple similar mongoose schemas into a single schema

I have a server which stores records representing Objects, and which uses Mongoose to manage these records. I want to be able to query/update/etc. all objects with a simple API (i.e. a single endpoint). Different types of Objects have some identical attributes, and some different attributes, so a single, static Object schema won't do. Instead, I still want to have a single schema, but I want to be able to change it slightly by adding/deleting fields when I create each new Object, with the fields which are/aren't present depending on the type of the Object. I don't want a mixed schema, because I want error validation for each type of Object. I want a single schema (as opposed to a different schema for each type of Object) so that I can just do



Object = mongoose.model('Object', ObjectSchema);
Object.findOne({objectType: "type1"}, function(err, model) {
...
});


So basically, I want field validation, while still maintaining some flexibility for attributes, and a single point to query/update/etc. my Object records. If I change the schema with each new Object, recompile it into a model, and create a new instance of that model, will all the instances of the different models (compiled from different modified versions of the same schema) still be queryable as above?


Obviously, I'm new to Mongoose. I just talked a lot about the schema here, and I honestly don't know whether I should have used the word "model" in place of "schema" in some places. I just don't know how I can accomplish all of this. Let me know if I make no sense.


Handling Socket.io to fail gracefully if the .js files cannot be loaded in with AJAX

I've built a simple Node Socket.io file that I'm using to post requests to to update a Perl application hooked up to it.


Example code in my Perl template file:



function start_io_service() {
socket = io("http://10.5.17.194:5892");
var current_user = $('#user-name').text();

console.log(socket); // For Debugging


// Handler to send back a username to the node application
socket.on('user-query', function (msg) {
// Send username
socket.emit('username', { username: current_user });
});
}


The Socket.io.js is loaded in using jQuery $getScript so I can handle if the Node server isn't running (which isn't required for 90% of the functionality of the Perl app).



$.getScript( "http://ift.tt/1EwBZ8z" )
.done(function( script, textStatus ) {
console.log( "It worked" );
})
.fail(function( jqxhr, settings, exception ) {
console.log("It didn't"); // This never appears
});


The .fail() method of getScript is completely ignored if the server isn't running when trying to load in the socket.io.js file from the server and I get the following error in my chrome console:



GET http://ift.tt/1LON9G7 net::ERR_CONNECTION_REFUSED


Even if I wrap the entire thing in a try and catch block it still doesn't change anything.


All I want is to ensure no errors appear and I get a simple console message instead. (The users of the system wouldn't be happy to see any sort of big red error message and would raise issues constantly).


Please note, if the server is running I get no issues and the app works, it's just handling the scenario that the server isn't running that I'm trying to solve.


Ideas?


Can't retrieve data from mongoDB with Node.js

I'm pretty new in Node.js and I have this project. Basically I have some data sits in a mongoDB collection("data") and I'm trying to get that data and display it on the browser.


Here is what I've got so far;



var MongoClient = require('mongodb').MongoClient
,format = require('util').format;
var sys = require ("sys");
my_http = require("http");

my_http.createServer(function(request, response){
sys.puts("Touched !!");
response.writeHeader(200, {"Content-Type": "text/plain"});
response.write(extractData()).toString();
response.end();
}).listen(8080);
sys.puts("Server is running on 8080"); // Server kicks in...np

function extractData(){

MongoClient.connect('mongodb://127.0.0.1:27017/mongoDB', function(err, db){
if (err){
console.log("Can't Connect to DB !!");
}else {
console.log("Connected to DB !!"); // connects to DB, np
db.data.find({}, function(err, data){ // .find is the problem
if (err || !data) console.log("No Data Found");
else data.forEach(function (data){
console.log(data);
});
}).toArray();
}
});
}


And after I run "node server.js" and refresh the already open localhost:8080, I get this;



Server is running on 8080
Touched !!
Touched !!
Connected to DB !!

d:\Projects\SCRIPTS\mdp.scripts.testing-tools\jsFinderWmongoDB\node_modules\mongodb\lib\mongodb\mongo_client.js:475
throw err
^
TypeError: Cannot call method 'find' of undefined
at d:\Projects\SCRIPTS\mdp.scripts.testing-tools\jsFinderWmongoDB\server.js:21:21
at d:\Projects\SCRIPTS\mdp.scripts.testing-tools\jsFinderWmongoDB\node_modules\mongodb\lib\mongodb\mongo_client.js:4
72:11
at process._tickCallback (node.js:415:13)


Don't understand why there is a problem with .find() and of course can't display any data...


Any ideas?


Using $timeout, scope is updated running localhost, but not remotely

I want to walk through an array slowly, doing something asynch for each element and present status as I go. Running on a local node server, I can see the status appear as expected, but when the same code is served from parseapps.com, no status appears. Any ideas why?


In the controller ...



function doSomethingSlow(inputArray, cursor) {
cursor = (cursor === undefined)? 0 : cursor;
var inputLength = inputArray.length;
var input = inputArray[cursor];
doSomethingAsynch(input).then(function(result) {
$timeout(function(){
$scope.status = result;
if (cursor < inputLength-1 && $scope.continue) {
doSomethingSlow(inputArray, cursor+1);
}
}, 1000);
}, function(error) {
alert("error");
});
}


In the mark-up ...



<div class="row" ng-if="status">
<div class="col-sm-12">
<div class="alert alert-success">{{status}}</div>
</div>
</div>


I figure the problem has something to do with when and how scope is applied in the timeout, but I don't understand enough to fix it. Besides, why would the server matter? I've tested in Chrome and Safari, on local and remote server. The function works in all cases, but in the remote case, the UI doesn't get updated.


I'd be happy if someone can suggest a better design. The cursor and the $timeout, etc seem pretty clunky and verbose for what sounds like a simple thing.


Converting string contaning array of arrays into JSON object

I have an API that returns me a string that contains an array of arrays. The arrays contians strings, like here:


"[['cat','mouse'],['duck','fish'],['lion','zebra']]"


and I want to convert it into a JSON object.


I've tried JSON.parse, but it's giving me an error



Blockquote [['+00:00 (Etc/GMT)','+00:00 (Etc/GMT)'],['+03:00 (Europe/Kaliningrad)','+03:0 ^ SyntaxError: Unexpected token '



The string that im trying to turn into an object is this one:



"[['+00:00 (Etc/GMT)','+00:00 (Etc/GMT)'],['+03:00 (Europe/Kaliningrad)','+03:00 (Europe/Kaliningrad)'],['-01:00 (Etc/GMT+1)','-01:00 (Etc/GMT+1)'],['AKST (America/Anchorage)','AKST (America/Anchorage)'],['ART (America/Argentina/Buenos_Aires)','ART (America/Argentina/Buenos_Aires)'],['AST (America/Puerto_Rico)','AST (America/Puerto_Rico)'],['AST (Asia/Baghdad)','AST (Asia/Baghdad)'],['AST (Atlantic/Bermuda)','AST (Atlantic/Bermuda)'],['BRT (America/Sao_Paulo)','BRT (America/Sao_Paulo)'],['CET (CET)','CET (CET)'],['CET (Europe/Amsterdam)','CET (Europe/Amsterdam)'],['CET (Europe/Brussels)','CET (Europe/Brussels)'],['CET (Europe/Budapest)','CET (Europe/Budapest)'],['CET (Europe/Madrid)','CET (Europe/Madrid)'],['CET (Europe/Oslo)','CET (Europe/Oslo)'],['CET (Europe/Paris)','CET (Europe/Paris)'],['CET (Europe/Prague)','CET (Europe/Prague)'],['CET (Europe/Vienna)','CET (Europe/Vienna)'],['CET (Europe/Warsaw)','CET (Europe/Warsaw)'],['CET (Europe/Zurich)','CET (Europe/Zurich)'],['CLST (America/Santiago)','CLST (America/Santiago)'],['COT (America/Bogota)','COT (America/Bogota)'],['CST (America/Chicago)','CST (America/Chicago)'],['CST (America/Costa_Rica)','CST (America/Costa_Rica)'],['CST (America/Mexico_City)','CST (America/Mexico_City)'],['CST (Asia/Shanghai)','CST (Asia/Shanghai)'],['CST (Asia/Taipei)','CST (Asia/Taipei)'],['CST (Australia/Adelaide)','CST (Australia/Adelaide)'],['EAT (Africa/Nairobi)','EAT (Africa/Nairobi)'],['EET (EET)','EET (EET)'],['EET (Europe/Istanbul)','EET (Europe/Istanbul)'],['EET (Europe/Kiev)','EET (Europe/Kiev)'],['EST (America/Indiana/Indianapolis)','EST (America/Indiana/Indianapolis)'],['EST (America/New_York)','EST (America/New_York)'],['EST (Australia/Brisbane)','EST (Australia/Brisbane)'],['EST (Australia/Melbourne)','EST (Australia/Melbourne)'],['EST (Australia/Sydney)','EST (Australia/Sydney)'],['GMT (Europe/Dublin)','GMT (Europe/Dublin)'],['GMT (Europe/London)','GMT (Europe/London)'],['GST (Asia/Dubai)','GST (Asia/Dubai)'],['HKT (Asia/Hong_Kong)','HKT (Asia/Hong_Kong)'],['HST (Pacific/Honolulu)','HST (Pacific/Honolulu)'],['ICT (Asia/Bangkok)','ICT (Asia/Bangkok)'],['IST (Asia/Jerusalem)','IST (Asia/Jerusalem)'],['IST (Asia/Kolkata)','IST (Asia/Kolkata)'],['JST (Asia/Tokyo)','JST (Asia/Tokyo)'],['KST (Asia/Seoul)','KST (Asia/Seoul)'],['MSK (Europe/Moscow)','MSK (Europe/Moscow)'],['MST (America/Denver)','MST (America/Denver)'],['MST (America/Phoenix)','MST (America/Phoenix)'],['MST (MST)','MST (MST)'],['MYT (Asia/Kuala_Lumpur)','MYT (Asia/Kuala_Lumpur)'],['NZDT (Pacific/Auckland)','NZDT (Pacific/Auckland)'],['PET (America/Lima)','PET (America/Lima)'],['PHT (Asia/Manila)','PHT (Asia/Manila)'],['PST (America/Los_Angeles)','PST (America/Los_Angeles)'],['PYST (America/Asuncion)','PYST (America/Asuncion)'],['SAST (Africa/Johannesburg)','SAST (Africa/Johannesburg)'],['SGT (Asia/Singapore)','SGT (Asia/Singapore)'],['TJT (Asia/Dushanbe)','TJT (Asia/Dushanbe)'],['UTC (UTC)','UTC (UTC)'],['VET (America/Caracas)','VET (America/Caracas)'],['WET (Europe/Lisbon)','WET (Europe/Lisbon)'],['WST (Australia/Perth)','WST (Australia/Perth)']]"

How to configure mqtt.js to connect to iot.eclipse.org over websockets

Edit: My issue is now this. I can connect to iot.eclipse.org using http://ift.tt/1AB7hth, using port 80. When I connect via a browsified mqtt.js client I am getting the following error :



WebSocket connection to 'ws://iot.eclipse.org/' failed: Error during WebSocket handshake: Unexpected response code: 200



I've tried ports 8080, 8000, 1883 and 80, without any luck. Any suggestions?


------------ Original question below -----------


I want to connect with a mqtt broker using mqtt over websockets. My client will need to run in a browser.


TO achieve this I am using mqtt.js library and am following these instructions.


Everything works when running against the public broker at broker.mqttdashboard.com. However when I connect to the public brokers at iot.eclipse.org and test.mosquitto.org I get HTTP errors.


I think the problem is incorrect configuration of the client when running against the second two brokers, but I'm struggling to find any help.


Heres the configuration, is there anyone out there who can help me?



// Works fine
var options = {
host: "broker.mqttdashboard.com",
port: 8000
};

// Doesn't work
/*var options = {
host: "m2m.eclipse.org",
protocolId: 'MQIsdp',
protocolVersion: 3
};*/

// Doesn't work
/*var options = {
host: "test.mosquitto.org",
protocolId: 'mosqOtti',
protocolVersion: 3
};*/

var client = mqtt.connect(options);


Let me know if theres any more information you need!


Mark


Control-Flow with NodeJS and Sequelize

I have the following function:



function retrieveNotifications(promotions) {
promotions.forEach( function(promotion) {

//find all notification groups that have to be notified
db
.Notification
.findAll()
.then(function (notifications) {
//some code that adds notifications to an object
});
});
};


How can I restructure it to wait till all notifications are added to the object. I can't use .then because it would be called multiple times because of the forEach


Writing png after capturing from webcam in node-webkit not working

I am taking snapshot in html5 using the following code.



window.takeSnapshot = function(){
$("body").append("<canvas id='dummyCanvas' class='canvas' style='display: none'></canvas>");
var canvas = document.getElementById("dummyCanvas");

canvas.width = videoWidth;
canvas.height = videoHeight;

var context = canvas.getContext("2d");
var type = mediaType;
var tp = tupple;

context.drawImage(videoElement, 0, 0, videoWidth, videoHeight);

var contents = canvas.toDataURL('image/png');
var dt = new Date();
Message.showProgress();
var time = dt.getHours() + "_" + dt.getMinutes() + "_" + dt.getSeconds();
var file = {name: "Snapshot_" + time + ".png", contents: contents, recorded: true};
var id = "attachment_" + window.Guid();
var icon = (type==ContentTypes.Video)?("video.png"):((type==ContentTypes.Audio)?"audio.png":"image.png");
$("#attachments").append("<tr id='"+id+"'><td align='right'><img src='assets/images/progress.gif' style='width:16px'/></td><td><img src='assets/images/" + icon + "' style='width: 14px;' /></td><td style='font-size: 8pt; font-family: Arial; font-weight: bold;' style='text-decoration:none; color: #000000'>"+file.name+"</td></tr>");
Logger.log("Uploading " + file.name + " ...", LogTypes.INFO);
$("#mediaPanel").remove();
$("#attachmentPopup").show();
window.stream.stop();

var callback = function(){
Logger.log("Upload completed for " + file.name + " !", LogTypes.INFO);
CWDocumentWriter.addAttachment(tp, file.name, type);
$("#"+id).find('td').eq(0).html("<a href='javascript:void(0)' title='Delete attachment' onclick='window.deleteAttachment(["+tp[0]+","+tp[1]+","+tp[2]+","+tp[3]+"],\""+file.name+"\", event)'><img src='assets/images/delete.png' style='width:16px'/></a>");
$("#"+id).find('td').eq(2).html("<a href='javascript:void(0)' title='"+file.name+"' onclick='window.showContent(\"" + file.name + "\", " + type + ")'>"+file.name+"</a>");
Message.hideProgress();

};

if(Cloud.isLive())
Cloud.writeFile(file, contents, callback);
else{


var canvasImage = canvas.toDataURL("image/png").split(',')[1];
var decodedImg = window.atob(canvasImage);
var img = new Buffer(decodedImg, encoding='base64');

file.contents = img;
StorageManager.writeImageFile(file, contents, callback);
}
};


The image is uploaded to the cloud or saved on the local storage (using nodejs functions) depending upon the live or dead internet. It works fine in uploading the image data to the cloud and I can save and see the image back. But in the case of local hard drive it is not working. The image seems to be corrupted. Here is how I am saving it.



StorageManager.writeImageFile = function(file, data, callback){

if(!UserManager.isLoggedIn()){
UserManager.login();
return;
}

var key = ProjectManager.projectName;
var dir = Settings.USER_FOLDER + "/" + key + "/" + "media";

data = window.encode64(file.contents);

fs.writeFile(dir + "/" + file.name, data, "base64", function(err){});

callback();
};


I have tried several approaches but it seems to be not working correctly. The image file is written in the hard drive but it is corrupted. Please help me to resolve this problem.


Jade Mixin for List

I'm trying to create a jade mixin where I can input the number of items in a list.


Example,



mixin list(n, text)
.list
a(href="#") #{text}
a(href="#") #{text}
.....n times


If I call the mixin like this



+list(4, 'hello')


the outputted html should resemble:



<div class="list">
<a href="#">hello</a>
<a href="#">hello</a>
<a href="#">hello</a>
<a href="#">hello</a>
</div>


How could I achieve this (with a loop)?


How do you stop a function when an Error object is received?

How do I stop the function at the point an error occurred.


I am making an http post call. I have constructed an error-first style callback function.


How do I stop the callback function if an Error object was passed in it? In my use case, I need to stop regardless of error type as I need the data object for subsequent chain of callback functions.


Is it simply return? I have read what return does on a higher level so hoping to get confirmation if my code is right for what I would like to achieve.


I just want to ensure the proceeding callback functions don't continue as they wont be passed any data objects, therefore, will all be 'errors'


server.js



var request = function(callback) {
// HTTP call to server
},
function (error, response, body) {
if (!error && response.statusCode === 200) {
// processed and created data object
return callback(null, data)
}
else {
console.log(error.stack)
return callback(error) ;
}
})
};
var requestSync = Meteor.wrapAsync(request);


var callback = function(error, data, callback) {
if (error) {
// How do I properly stop this function?
return callback(new Error('custom message I send to client'))
}
else {
// doing something with data object..
}
}


The functions are invoked within my method.



try {
var resultOne = requestSync()
var resultTwo = callback(resultOne)
// more async callback functions will reside here
} catch (e) {
console.error('error occured somehwere = ' + e);
} finally {
//
}

Caching header with mongodb timestamp

Found this issue when testing caching using mongodb as our data storage. The last-modified date is being correctly, but it by its specification it doesn't include milliseconds thus when the node JS controller tries to compare them they are different:



Fri Feb 27 2015 09:15:00 GMT+0000 (GMT) - Mongo DB date
Fri Feb 27 2015 09:15:00 GMT+0000 (GMT) - if-modified-since


Controller values:



1425028500987 - Mongo DB date
1425028500000 - if-modified-since


As you can see the mongodb includes milliseconds. Has anybody a nice way to clean up the date to reset milliseconds?


Thanks.


J


Elasticsearch query for matching two parameters at the same time

I have to search two fields in a DB using elasticsearch where i should be getting total hits isequal to the sum of individual field search. I did it on port 9200 like this and its working. How to write a must match code for this.



http://localhost:9200/indexname/typename/_search?q=Both:Yes++Type:Comm


Where Both is one field and Comm is another.


Thank you


Stylus inline SVG without base64

How do I inline SVG images in CSS with Stylus without the images being converted to Base64 strings?


Like



background: url('data:image/svg+xml;utf8,<svg>[...]</svg>');


instead of:



background: url('data:image/svg+xml;base64,PD94bWwg[...]');


When I use stylus.url() the image is converted to Base64.


Node.js - How to sync files to/from GitHub

I am just beginning to work with Node.js.


I have run npm init.


One of the items it prompts me for is a Git repository. I provided the address to a new (only containing the README.md) public GitHub repository.


If I create a new file from my desktop and check it in to the repository -- how does that file get synced to my server running Node.js.


Is there an npm command to do so or is it handled automatically?


Grunt trigger nodejs module and pass in parameter

I want to write a grunt file so that when a file is added to a image folder, grunt will trigger the following nodejs image resize module GruntHandler, passing in the path to the newly added file.


Has anyone had any experience with this?


I am somewhat lost here as how to set it all up and write the grunt file to do this.


This is the code I want to trigger.



// dependencies
var async = require('async');
var gm = require('gm').subClass({ imageMagick: true });
var util = require('util');
var fs = require("fs");

var _800px = {
width: 800,
destinationPath: "large"
};

var _500px = {
width: 500,
destinationPath: "medium"
};

var _200px = {
width: 200,
destinationPath: "small"
};

var _45px = {
width: 45,
destinationPath: "thumbnail"
};

var _sizesArray = [_800px, _500px, _200px, _45px];

var len = _sizesArray.length;

// handler for dev environment

exports.GruntHandler = function (event, context) {
// Read options from the event.
console.log("Reading options from event:\n", util.inspect(event, {depth: 5}));

var srcFile = event; // file being sent by grunt ---> string url to file

var dstnFile = "/dst";

// Infer the image type.
var typeMatch = srcFile.match(/\.([^.]*)$/);
if (!typeMatch) {
console.error('unable to infer image type for key ' + srcFile);
return;
}
var imageType = typeMatch[1];
if (imageType != "jpg" && imageType != "png") {
console.log('skipping non-image ' + srcFile);
return;
}

// Download the image from S3, transform, and upload to same S3 bucket but different folders.
async.waterfall([
function download(next) {
// Read the image from local file and pass into transform.

fs.readFile(srcFile, function (err, data) {
if (err) {
next(err);
}
next(data);
});
},

function transform(response, next) {


for (var i = 0; i<len; i++) {

// Transform the image buffer in memory.
gm(response.Body, srcFile)
.resize(_sizesArray[i].width)
.toBuffer(imageType, function(err, buffer) {
if (err) {
next(err);

} else {
next(null, response.ContentType, buffer);
}
});
}
},

function upload(contentType, data, next) {

for (var i = 0; i<len; i++) {

// Stream the transformed image to a different folder.
fs.writeFile(dstnFile + "/" + _sizesArray[i].destinationPath + "/" + fileName, function (err, written, buffer) {
if (err) {
next(err);
}
});
}
}

], function (err) {
if (err) {
console.error(
'---->Unable to resize ' + srcFile +
' and upload to ' + dstnFile +
' due to an error: ' + err
);
} else {
console.log(
'---->Successfully resized ' + srcFile +
' and uploaded to ' + dstnFile
);
}

context.done();
}
);

console.log(" grunt handler called!");
};

issues while installing engine.io node js

i am trying to install engine.io (http://ift.tt/1wqR3hg)


I am getting the following error


C:\Windows\system32>npm install engine.io



ws@0.5.0 install C:\Windows\system32\node_modules\engine.io\node_modules\ws (node-gyp rebuild 2> builderror.log) || (exit 0)



C:\Windows\system32\node_modules\engine.io\node_modules\ws>node "C:\Program File s (x86)\nodejs\node_modules\npm\bin\node-gyp-bin\....\node_modules\node-gyp\bi n\node-gyp.js" rebuild engine.io@1.5.1 node_modules\engine.io ├── base64id@0.1.0 ├── debug@1.0.3 (ms@0.6.2) ├── engine.io-parser@1.2.1 (blob@0.0.2, arraybuffer.slice@0.0.6, after@0.8.1, ba se64-arraybuffer@0.1.2, utf8@2.0.0, has-binary@0.1.5) └── ws@0.5.0 (options@0.0.6, ultron@1.0.1, nan@1.4.3)


Kindly assist.Thanks


Unit testing validation with express-validator

How can I unit test my validations that are done using express-validator?


I have tried creating a dummy request object, but I get the error: TypeError: Object #<Object> has no method 'checkBody'. I am able to manually test that the validation works in the application.


Here is what I have tried:



describe('couponModel', function () {
it('returns errors when necessary fields are empty', function(done){
var testBody = {
merchant : '',
startDate : '',
endDate : ''
};
var request = {
body : testBody
};
var errors = Model.validateCouponForm(request);
errors.should.not.be.empty;
done();
});
});


My understanding is that the checkBody method is added to the request object when I have app.use(expressValidator()) in my express application, but as I am only testing that the validation is working in this unit test I do not have an instance of the express application available, and the validation method that I am testing is not called directly from it anyway as it is only called through a post route, which I do not want to call for a unit test as it involves a database operation.