Backtick in ECMASCRIPT : Unexpected Token Illegal - node.js

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.

Related

Gulp-Sourcemaps, SyntaxError: Unexpected token >

Gulp / npm noobie here.
I'm trying to use gulp-sourcemaps, and for some reason, it crashes on var sourcemaps = require('sourcemaps').(It crash only when this line's in the file)
gulpfile:
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('generateApp', function () {
return gulp.src([some paths...])
.pipe(sourcemaps.init())
.pipe(concat('app.min.js'))
.pipe(uglify())
.pipe(sourcemaps.write())
.pipe(gulp.dest(path...));
});
Error :
C:\Projets\node_modules\strip-bom\index.js:2
module.exports = x => {
^
SyntaxError: Unexpected token >
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 Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (C:\Projets\node_modules\gulp-sourcemaps\src\init.js:10:14)
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)
Has anyone encounter this type of error?
I tried to google it, without any success.
I just started getting the same error and fixed it by replacing the code in C:\Projects\node_modules\strip-bom\index.js with this:
'use strict';
module.exports = function (x) {
if (typeof x !== 'string') {
throw new TypeError('Expected a string, got ' + typeof x);
}
// Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
// conversion translates it to FEFF (UTF-16 BOM)
if (x.charCodeAt(0) === 0xFEFF) {
return x.slice(1);
}
return x;
};
Then, I had to run npm rebuild node-sass to get it to work again. It seems to be an issue with an older version of the Strip-bom node module.
For more info, check this out: https://github.com/sindresorhus/strip-bom/commit/e2a3c3b83706ee5baac284f3862d3f6b9e1564e5
UPDATED ANSWER:
This error is caused by using an older version of Node. The Strip-bom module is now using ES2015 (ES6) syntax which requires Node 5.0+. (See Node's ES2015 support list here)
To test your version of Node, run:
node -v
If it's less than 5.0, you'll need to update it. You can download the newest version of Node here:
https://nodejs.org/en/
After installing the new version of Node, I still needed to run npm rebuild node-sass to get Gulp up and running again.
The former answer will still work if you don't want to update your Node version, however, as Louis pointed out, manually editing node module files is not a best-practice.

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.

nodejs automatic url to folder mapping

I'm new to nodejs. What I want is to have several apps run at different context roots based on the directory structure. (all must be online at the same time)
For Example:
dir1
|____test1.js
|____test2.js
dir2
|____test1.js
|____test2.js
http://localhost:3000/dir1/test1
http://localhost:3000/dir1/test2
http://localhost:3000/dir2/test1
http://localhost:3000/dir2/test2
It's desired to automatically discover the scripts and create the end points.
I could not find such a feature in a test framework like mocha.
Can you please guide me with nodejs server url mapping?
Update:
I've tried this:
var express = require('express');
var app = express();
entrypoints = ["/a", "/b", "/c"]
entrypoints.forEach(function(val, index, arr){
app.get(val, function(req, res){
x = require("."+val+".js");
x.handle(req, res);
});
}
app.listen(3000);
where each a.js, b.js, c.js implements the handle but it fails; it does not like putting app.get inside a loop:
app.listen(3000);
^^^
SyntaxError: Unexpected identifier
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:906:3

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/

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