lundi 30 mars 2015

AZURE + SOCKET.IO: How do I know which port my Web App is using?

I went to a Hackathon last weekend and a Microsoft recruiter set me up with Azure for my Node.js project.


We used Socket.io with my project and had a hard time connecting the Client to the Server because we didn't know which port to connect to...


On our WebApp (not Azure VM), we had the following code:



var port = process.env.port || 3000;


On the client side of Socket.io, I had to specify an ip address to use along with it's port. I tried:



var socket = io('http://ift.tt/1OPOP6k'); //And
var socket = io('http://IP.AD.DRE.SSS'); //And even a different Port
var socket = io('http://ift.tt/1BVWHZS'); //And 443 and 80


And every iteration... I had to be doing something wrong. We ended up switching over to Digital Ocean because I knew how to use it but I really wanted to get this working.


Any Ideas?


UPDATE:

I changed it to 80 and my current error is: "Access Control Allow Origin." Note: My client is running on a server.


UPDATE 2: Return of the OP

Unfortunately, the CORS package for Node did not do the trick...


Some more info:

I'm not using Express or Connect. My server is on Azure (as an Azure Web App). My Client was on Localhost (Thanks to WebStorm).


Node.js - wait for process.exit() to execute after earlier code is finished

In my node.js application I want to write some data to a logfile when the server is shutdown (thus when CTRL+C has been done in the cmd). The problem is that the process.exit() is called before the writing to the file is finished. I tried using a callback and jQuery $.Deferred.resolve(), but to no avail: probably because the file-write is async but I'd like to keep it asynchronous.

The callback code:



if (process.platform === "win32"){
var rl = readLine.createInterface ({
input: process.stdin,
output: process.stdout
});

rl.on ("SIGINT", function (){
process.emit ("SIGINT");
});

}

process.on ("SIGINT", function(){
var stopServer = function() {
//this happens way too early, the logger.log has not written it's data yet
process.exit();
};

var logServerStop = function(callback) {
logger.log("SERVER SHUTDOWN: ", true);
logger.log("-----------------------------------------");
logger.log("");
callback();
};
logServerStop(stopServer);

});


And the logger.log code:



var fs = require('fs');
var filename = './output/logs/logfile.txt';

exports.log = function(data, addDate){
if (typeof addDate === 'undefined') { myVariable = false; }
var now = new Date();
var date = now.getDate() + "-" + (now.getMonth() + 1) + "-" + now.getFullYear();
var time = now.getHours() + now.getMinutes();

if(addDate){
data = data + date + " " + now.toLocaleTimeString();
}
var buffer = new Buffer(data + '\r\n');

fs.open(filename, 'a', function( e, id ) {
if(e){
console.log("Foutje: " + e);
}
else{
fs.write( id, buffer, 0, buffer.length, null, function(err){
if(err) {
console.log(err);
} else {
console.log("De log file is aangevuld.");
}
});
}

});
};


I'd also like to keep the log-function as it is (so I wouldn't like having to add a callback-function parameter, I'd like my problem to be handled in the callback code. Thanks in advance.


Edit 1



process.on ("SIGINT", function(){
logger.log("SERVER SHUTDOWN: ", true);
logger.log("-----------------------------------------");
logger.log("", false, function(){
process.exit();
});

});


And the logger.log changes:



exports.log = function(data, addDate, callback){
if (typeof addDate === 'undefined') { myVariable = false; }
var now = new Date();
var date = now.getDate() + "-" + (now.getMonth() + 1) + "-" + now.getFullYear();
var time = now.getHours() + now.getMinutes();

if(addDate){
data = data + date + " " + now.toLocaleTimeString();
}
var buffer = new Buffer(data + '\r\n');

fs.open(filename, 'a', function( e, id ) {
if(e){
console.log("Foutje: " + e);
}
else{
fs.write( id, buffer, 0, buffer.length, null, function(err){
if(err) {
console.log(err);
} else {
console.log("De log file is aangevuld.");
}
});
}

});
if(typeof(callback)=='function'){ callback(); }
};

Object #

I working through the Lynda.com course on the MEAN stack and this error keeps occurring. I'm not real sure where to look. I have already scoured through numerous Google pages looking for anything that may give me a clue


This is where I call findUser.



module.exports = function() {
var passport = require('passport');
var passportLocal = require('passport-local');
var userService = require('../services/user-service');

passport.use(new passportLocal.Strategy({usernameField: 'email'}, function(email, password, next) {
userService.findUser(email, function(err, user) {
if (err) {
return next(err);
}
if (!user || user.password !== password) {
return next(null, null);
}
next(null, user);
});
}));

passport.serializeUser(function(user, next) {
next(null, user.email);
});

passport.deserializeUser(function(email, next) {
userService.findUser(email, function(err, user) {
next(err, user);
});
});
};


This is the error that I get when trying to "login" with user information verified in the database.



TypeError: Object #<Object> has no method 'findUser'
at Strategy.module.exports [as _verify] (/home/ubuntu/workspace/auth/passport-config.js:7:17)
at Strategy.authenticate (/home/ubuntu/workspace/node_modules/passport-local/lib/strategy.js:90:12)
at attempt (/home/ubuntu/workspace/node_modules/passport/lib/middleware/authenticate.js:341:16)
at authenticate (/home/ubuntu/workspace/node_modules/passport/lib/middleware/authenticate.js:342:7)
at Layer.handle [as handle_request] (/home/ubuntu/workspace/node_modules/express/lib/router/layer.js:82:5)
at next (/home/ubuntu/workspace/node_modules/express/lib/router/route.js:110:13)
at Route.dispatch (/home/ubuntu/workspace/node_modules/express/lib/router/route.js:91:3)
at Layer.handle [as handle_request] (/home/ubuntu/workspace/node_modules/express/lib/router/layer.js:82:5)
at proto.handle.c (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:267:22)
at Function.proto.process_params (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:321:12)

How can I require the module into my file?

I create an express project and the directory structure like:



/
- model
db.js
- routes
users.js
app.js


In ./model/db.js, I have a MySql connection:



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

connection.connect();


And in ./routes/users.js, I need to query database:



var express = require('express');
var router = express.Router();
var db = require('./model/db.js'); // always cannot find the module....

router.route('/')
.get(function (req, res) {
connection.query(
'select * from user',
function (err, rows, fields) {
if (err) {
res.status(500).send('error');
} else {
res.send({
result : 'success',
err : '',
err_type : '',
fields : fields,
rows : rows,
length : rows.length
});
}
}
)
});


module.exports = router;


But the debugger always says that Cannot find the module './model/db.js'.


I am new to nodejs, can anybody tell me how to require the db.js into routes file? Thanks a lot.


updating a subdocument inside nested array using $addToset followed by $pull


{"layers":[{"layer name":"layer1","layer_vals":[{"name":"val1","updated":"value"}]}]}


I have a JSON document like the one above.I wish to change the value of updated everytime an operation is performed on that subdocument.As can be seen the document is nested inside two arrays.I am planning to use a $addToSet to first add the new updated value and then do $pull to remove the old one.But I am getting an error saying I cannot perform both operation on same document.Is there any solution to this? Also any other suggestions on solving the above problem would be great too


Error in OpenShift: "phantomjs-node: You don't have 'phantomjs' installed"

I successfully created a script using phantomjs-node in local and I would like to host in on OpenShift.


The thing is when I started my script hosted, I had this strange error:



phantom stderr: execvp(): No such file or directory phantomjs-node: You don't have 'phantomjs' installed



But as you can see, I put the dependancies in the package.json file:



"dependencies": {
"express": "~3.4.4",
"phantom": "*",
"phantomjs": "*"
},


Any suggestions?


npm ssh error doesn't replicate from shell

When trying npm install, I get error:



1206 error node v0.12.0
1207 error npm v2.7.4
1208 error code 128
1209 error Command failed: git clone --template=/root/.npm/_git-remotes/_templates --mirror ssh://git@git.spindle.factfiber.com/schematist-postgres.git /root/.npm/_git-remotes/ssh-git-git-spindle-factfiber-com-schematist-postgres-git-8e4b2071
1209 error ssh: Could not resolve hostname git.spindle.factfiber.com: Name or service not known


However, when I try the very command reported from the shell:



git clone --template=/root/.npm/_git-remotes/_templates --mirror ssh://git@git.spindle.factfiber.com/schematist-postgres.git /root/.npm/_git-remotes/ssh-git-git-spindle-factfiber-com-schematist-postgres-git-8e4b2071


It works:



Cloning into bare repository '/root/.npm/_git-remotes/ssh-git-git-spindle-factfiber-com-schematist-postgres-git-8e4b2071'...
remote: Counting objects: 47, done.
remote: Compressing objects: 100% (39/39), done.
remote: Total 47 (delta 20), reused 0 (delta 0)
Receiving objects: 100% (47/47), 13.05 KiB, done.
Resolving deltas: 100% (20/20), done.


I tried this a couple times in case it was a temp dns glitch. Does anyone know what could be happening?