Creating an express project first run gives errors - node.js

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/

Related

Angular universal build breaks with the following error: throw Error("not supported");

Running the following command : npm run build:ssr && npm run serve:ssr runs 3 different compilation stages but on the last one it returns the following error resulting to the server not starting.
Error: not supported
at Root.loadSync (/var/www/html/stage/node_modules/#grpc/proto-loader/node_modules/protobufjs/src/root.js:234:15)
at Object.loadSync (/var/www/html/stage/node_modules/#grpc/proto-loader/node_modules/protobufjs/src/index-light.js:69:17)
at Object.<anonymous> (/var/www/html/stage/node_modules/#grpc/proto-loader/build/src/index.js:244:37)
at Module._compile (internal/modules/cjs/loader.js:721:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:732:10)
at Module.load (internal/modules/cjs/loader.js:620:32)
at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
at Function.Module._load (internal/modules/cjs/loader.js:552:3)
at Module.require (internal/modules/cjs/loader.js:657:17)
at require (internal/modules/cjs/helpers.js:22:18)
Environment and packages"
Angular CLI: 8.3.3
Node: 11.6.0
OS: linux x64
Angular: 8.2.5
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... platform-server, platform-webworker
... platform-webworker-dynamic, router, service-worker
My server.ts looks as follows
const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist');
const domino = require('domino');
const fs = require('fs');
const path = require('path');
const template = fs.readFileSync(path.join(__dirname, join(DIST_FOLDER, 'browser/index.html'))).toString();
const win = domino.createWindow(template);
global['window'] = win;
global['navigator'] = win.navigator;
global['Node'] = win.Node;
global['Event'] = win.Event;
global['Event']['prototype'] = win.Event.prototype;
global['document'] = win.document;
global["branch"] = null;
global['localStorage'] = localStorage;
Finally solved the problem.
1. Deleted problematic folder ./node_modules/#grpc/...
2. Manually uploaded a new #grpc folder with
#grpc
-- proto-loader
---- build/src/index.js
---- LICENCE
---- package.json
here's the repo to those who may find it useful
--> https://github.com/Gerald34/Angular-Universal-grpc
you can fix by adding process to your fake window in the server.ts file
win.process = process;
You can find more info in this article, with also other errors I encountered with Angular SSR + Firebase

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.

Koa-pg Can't find module pg

Hey so I'm trying to get Nodejs Koa to talk to postgres using the Koa-pg module, but I keep getting a 'Can't find module pg' error.
I've tried to follow the koa-pg examples, but have come up short...so any advice would on how to progress would be appreciated.
If created my app.js file as follows:
var koa = require('koa');
var route = require('koa-route');
var koaPg = require('koa-pg');
var roads = require('./controllers/roads');
var app = module.exports = koa();
app.use(route.get('/roads/bbox/', roads.bbox));
app.listen(3000);
console.log('listening on port 3000');
And then created my controller file as follows:
var credentials = require('../credentials.js');
var environment = credentials.dev;
app.use(koaPg('postgres://' + environment.user + '#' + environment.host + ':' + environment.port + '/' + environment.database))
module.exports.bbox = function * bbox(next) {
var result = yield this.koaPg.db.client.queryPromise('SELECT now()')
console.log('result: ', result)
this.body = result.rows[0].now.toISOString()
};
But I'm getting the following error:
module.js:338
throw err;
^
Error: Cannot find module 'pg'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:278:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (c:\Users\User\Documents\restful_koa\node_modul
es\koa-pg\index.js:12:27)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
This is only a personal project but I'd love to understand where i'm going wrong.
Cheers
As mentioned in the comments:
You need to install the pg module via npm install pg or npm install pg --save if you want to save it to package.json.
The reason you need to do this is koa-pg has co-pg as a dependency so when you install the former the latter is also installed. But pg is not a dependency of co-pg and that is why you have to install it separately.

Error when using vhost in express

My code for server.js is:
var express = require('express');
var ENV = process.env['NODE_ENV'] || 'development';
var config = require('./config')[ENV];
// The express server to listen for both the clients
var main = express();
// Main application
main.use(express.vhost('vypics', require('./web_app/app').app))
// Example sub domain
main.use(express.vhost('android.vypics',require('./android_app/app').app));
main.listen(3000);
console.log('started on 3000');
when I am running node server.js I am getting the following error.
/Users/saransh2012/Developer/vypics/node_modules/express/node_modules/connect/lib/middleware/vhost.js:30
if (!server) throw new Error('vhost server required');
^
Error: vhost server required
at Function.vhost (/Users/saransh2012/Developer/vypics/node_modules/express/node_modules/connect/lib/middleware/vhost.js:30:22)
at Object.<anonymous> (/Users/saransh2012/Developer/vypics/server.js:8:18)
at Module._compile (module.js:456:26)
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:901:3
Please help.....What Am i Doing wrong.
You'll get that error when the second argument to express.vhost is falsy.
My guess would be that either require('./web_app/app').app or require('./android_app/app').app (or both) is undefined.
The error was in the require('.web_app/app').app part as mentioned by robertklep.It was a very silly error on my part as i forgot to write the export for the app.
Sorry guys for such a silly error but sometimes those are the one very difficult to see.

cloud9 + mongodb + nodejs

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 :-)

Resources