cloud9 + mongodb + nodejs - node.js

I using cloud9 ide coding new project. When I deploy on cloudfoundry from cloud9ide. I have error
Application failed to start. Please note that CloudFoundry uses a different port to listen to. When calling 'listen()' use it like '.listen(process.env.PORT || process.env.VCAP_APP_PORT)'.
This is my source
var port = (process.env.VMC_APP_PORT || 3000);
var host = (process.env.VCAP_APP_HOST || 'localhost');
var http = require('http');
var env = process.env.VCAP_SERVICES ? JSON.parse(process.env.VCAP_SERVICES) : null;
var mongodata = env['mongodb-1.8'][0]['credentials'];
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n' + env);
}).listen(port, host);
This source have error when I get mongo object
var mongodata = env['mongodb-1.8'][0]['credentials'];
But not have this line deploy successful
Please help me !!
Thanks so much

As the error in the cloud9 console probably tells you (as it tells me when i try this :-) ):
haalasdoallalsakdl (CloudFoundry): [5/6] Crash log
============/logs/stderr.log============
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot read property '0' of undefined
at Object.<anonymous> (/var/vcap/data/dea/apps/haalasdoallalsakdl-0-8be0d413a9ec29a79f665d388ce414bd/app/server.js:7:35)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
So there is no entry in VCAP_SERVICES called like that. When I console.log the process.env variable, there isn't even any service listed.
So you'll have to install the mongodb service for your app. Fastest to do this is via the CF VMC tools (can't run this in cloud9 at the moment, so you'll have to install this locally):
vmc create-service mongodb --bind your_app_name
Then it'll start up fine.
N.B. You can probably fix this in the .yml file, but I don't know how to do this :-)

Related

Backtick in ECMASCRIPT : Unexpected Token Illegal

I am writing a small test code in an ExpressJs app. The code is as follows :
var express = require('express');
var app = express();
var dataFile = require('./data/data.json');
app.set('port', process.env.PORT || 3000);
app.get('/', function(req, res) {
var info = '';
dataFile.speakers.forEach(function(item) {
info += `<li>
<h2>${item.name}</h2>
<p>${item.summary}</p>
</li>
`;
});
res.send(`
<h1>My Meetups</h1>
${info}
`);
});
var server = app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
When I try to execute the command
node app/app.js
in Git bash terminal, I get the following error :
> E:\expressjs\app\app.js:11
> info += `<li>
> ^ SyntaxError: Unexpected token ILLEGAL
> at Module._compile (module.js:439:25)
> at Object.Module._extensions..js (module.js:474:10)
> at Module.load (module.js:356:32)
> at Function.Module._load (module.js:312:12)
> at Function.Module.runMain (module.js:497:10)
> at startup (node.js:119:16)
> at node.js:935:3
What I tried :
Checked node version : Using node 0.10.37
Tried running the node command with --harmony option as suggested : Same error
Tried visiting the ECMA compatibility table website : Wasn't able to search the right information
Am using the Atom Editor
What I suspect : Incompatible version of Node and ECMA
Can someone help with this ?
Thanks
Try this site. It shows all es6 features implemented in nodeJS
http://node.green/
My suspect is that you using very old version of node(almost all features gives error in node 0.10).
Try to upgrade into node6 and all should be OK.
Hope this helps.

Unhandled rejection TypeError when trying to promisify a node-mysql connection and query

I'm attempting to use bluebird's promisify with the node-mysql package. Node version is 4.2.4
var Promise = require('bluebird');
var mysqlClient = Promise.promisifyAll(require("mysql/lib/Connection").prototype);
Promise.promisifyAll(require("mysql/lib/Pool").prototype);
var connectionOptions = ({
host: 'localhost',
user: 'root',
password: '',
database: 'my_db'
});
var firstPost = "some sql here";
var results = [];
mysqlClient.connectAsync(connectionOptions).then(function(connection){
connection.query(firstPost, function(){
console.log('i reached line 26 of a node script. a minor miracle')
});
}).catch(function(err) {
console.log(err);
});
I get the error
[TypeError: Cannot read property 'socketPath' of undefined]
Stack trace:
Unhandled rejection TypeError: Cannot read property 'socketPath' of undefined
at Connection.connect (/vagrant/spam_smasher/node_modules/mysql/lib/Connection.js:87:32)
at Connection.tryCatcher (/vagrant/spam_smasher/node_modules/bluebird/js/release/util.js:11:23)
at Connection.ret [as connectAsync] (eval at <anonymous> (/vagrant/spam_smasher/node_modules/bluebird/js/release/promisify.js:184:12), <anonymous>:13:39)
at Object.<anonymous> (/vagrant/spam_smasher/bluebird.js:24:13)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:136:18)
at node.js:963:3
Why am I getting this error and/or how could I debug it further? I tried to remote debug it but am not sure what I'm looking at when I get a few steps down the prototype chain. The Async functions do appear to be attached to the MysqlClient object.
Remore debugging reveals that the following section in node-mysql's Connection.js file is throwing the error :
if (!this._connectCalled) {
this._connectCalled = true;
// Connect either via a UNIX domain socket or a TCP socket.
this._socket = (this.config.socketPath)
? Net.createConnection(this.config.socketPath)
: Net.createConnection(this.config.port, this.config.host);
socketpath is not something you need to define when using node-mysql directly
It seems the Bluebird docs are out of date. They miss that you also need ConnectionConfig to be available and so this was missing in my code, causing the error.
I chose to abandon this problem to preserve my sanity. There is further discussion here and you may also want to check out mysql-promise

Creating an express project first run gives errors

I installed express globally.
I have created a new project called helloExpress like this:
express helloExpress -c less
Installed all dependencies:
cd helloExpress
sudo npm install
Run the app:
node app.js
Output error:
/home/dev/projects/helloExpress/app.js:1
s., */,,var expr
^
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
SyntaxError: Unexpected token ,
at Module._compile (module.js:429:25)
at Object..js (module.js:459:10)
at Module.load (module.js:348:32)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:41)
Looking into the code of app.js it looks like this:
/**, * Module dependencies., */,,var express = require('express'), , routes = require('./routes'), , user = require('./routes/user'), , http = require('http'), , path = require('path');,,var app = express();// all environments,app.set('port', process.env.PORT || 3000);,app.set('views', __dirname + '/views');,app.set('view engine', 'jade');,app.use(express.favicon());,app.use(express.logger('dev'));,app.use(express.bodyParser());,app.use(express.methodOverride());,app.use(app.router);undefined app.use(require('less-middleware')({ src: __dirname + '/public' }));,app.use(express.static(path.join(__dirname, 'public')));,,// development only,if ('development' == app.get('env')) {, app.use(express.errorHandler());,},,app.get('/', routes.index);,app.get('/users', user.list);,,http.createServer(app).listen(app.get('port'), function(){, console.log('Express server listening on port ' + app.get('port'));,});,
As you can see there are , everywhere.
Is this a known bug or am I doing something wrong here?
As Jonathan Lonowski said in the comments, the Node.js version I used was too old.
I installed a newer version of Node.js by following this tutorial: http://slopjong.de/2012/10/31/how-to-install-the-latest-nodejs-in-ubuntu/

now.js : "Object has no method" error message when trying to start server.js

I installed node.js and now.js successfully.
For now.js, this is how I did:
npm install now -g
npm install now (had to add this one. Without it, I get a "Cannot find now..." error message)
When I start the node server and provide a server.js file like this:
var httpServer = require('http');
httpServer.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Node is ok');
res.end();
}).listen(8080);
console.log('Server runs on http://xxxxx:8080/');
Everything is fine.
Now, I'm trying to add to this file a basic use of now.js:
var nowjs = require("now");
var everyone = nowjs.initialize(httpServer);
everyone.now.logStuff = function(msg){
console.log(msg);
}
I create an index.html file in the same folder (for testing purposes)
<script type="text/javascript" src="nowjs/now.js"></script>
<script type="text/javascript">
now.ready(function(){
now.logStuff("Now is ok");
});
</script>
This time, this is what I get on the terminal when starting the server:
Server runs on http://xxxxx:8080/
[TypeError: Object #<Object> has no method 'listeners']
TypeError: Object #<Object> has no method 'listeners'
at Object.wrapServer (/home/xxxx/node_modules/now/lib/fileServer.js:23:29)
at [object Object].initialize (/home/xxxx/node_modules/now/lib/now.js:181:14)
at Object.<anonymous> (/home/xxxx/server.js:10:22)
at Module._compile (module.js:444:26)
at Object..js (module.js:462:10)
at Module.load (module.js:351:32)
at Function._load (module.js:309:12)
at module.js:482:10
at EventEmitter._tickCallback (node.js:245:11)
Please keep in mind that I'm an absolute beginner.
Thank you for your help
'npm install -g' installs modules at a global level, often with the intent of providing system-wide binaries for terminal usage. Think Ruby Gems. If you want to include a module as part of your project you need to remove the -g.
Also, your httpServer variable is not your server but rather the http module. createServer() returns a server object which you want to capture with a variable to use in your nowjs.initialize() method as follows:
var http = require('http')
, now = require('now')
// Returns an Http Server which can now be referenced as 'app' from now on
var app = http.createServer(
//... blah blah blah
)
// listen() doesn't return a server object so don't pass this method call
// as the parameter to the initialize method below
app.listen(8080, function () {
console.log('Server listening on port %d', app.address().port)
})
// Initialize NowJS with the Http Server object as intended
var everyone = nowjs.initialize(app)

process.nextTick error in node.js?

I am getting process.nextTick error on this very basic example of node.js.
Can someone please figure out?
Is node not able to start listening on port 8000?
# cat nodejs.js
net = require("net");
s = net.createServer();
net.on('connection', function (c) {
c.end('hello');
});
s.listen(8000);
# node nodejs.js
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Object #<Object> has no method 'on'
at Object.<anonymous> (/home/ec2-user/praveen/nodejs.js:4:5)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
at EventEmitter._tickCallback (node.js:192:40)
It's a typo in Ryan's slide! :-0
s/net.on/s.on/
It seems you're trying to capture an event on the library (net), but you should be looking at the connectionListener argument to createServer. Try this instead:
var net = require("net");
var server = net.createServer(function (c) {
c.end('Hello!'); // Implicitly fired on 'connection'
});
server.listen(8000);
For anyone else who might stumble here looking for why node pukes this error when they try to issue brunch watch --server, check and make sure you don't have any other servers running using the same port (i.e. in another shell).

Resources