vendredi 27 février 2015

router.get('/') on expressjs not working

i can't access to my express application's home page by '/' route pattern. it's working on /index e.g. My express version is 4.6.


I tried app.use('/*', router), but my application is not responding or 503 service temporarily unavailable. It's now working by '/index' pattern and other routes is working correctly. only '/' pattern is not working. :)


Here is my code snippet.





var http = require('http');

var express = require('express');
var app = express();

var router = express.Router();
app.use('/', router);

app.set('view engine', 'ejs');
app.set('views', './views');
app.use(express.static('./public'));

var bodyParser = require("body-parser");
app.use(bodyParser());

var fs = require('fs');

var clientSessions = require("client-sessions");

var form = require('express-form');
var field = form.field;

var sha1 = require('sha1');

var mysql = require('mysql');
var connection = mysql.createConnection({
host: process.env.OPENSHIFT_MYSQL_DB_HOST,
port: process.env.OPENSHIFT_MYSQL_DB_PORT,
user: process.env.OPENSHIFT_MYSQL_DB_USERNAME,
password: process.env.OPENSHIFT_MYSQL_DB_PASSWORD,
database: process.env.OPENSHIFT_GEAR_NAME
});

var multer = require('multer');
var done = false;

app.use(clientSessions({
secret: 'xxxxx'
}));

app.use(function(req, res) {
res.status(400);
res.render('pages/404');
});

// Handle 500
app.use(function(error, req, res, next) {
res.status(500);
res.render('pages/500');
});

//---
app.use(multer({
dest: 'public/uploads/',
rename: function(fieldname, filename) {
return filename + Date.now();
},
onFileUploadStart: function(file) {
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function(file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
done = true;
}
}));

//// --------------- start app routes --------------//
// ----- GET -----
router.get('/', function() { // THIS PATTERN IS NOT WORKING
console.log('hello world'); // this line is not working
connection.query(strQuery, function(err, rows) {
// res.render('pages/index');
});

});



Fill a typed array with .bin file content in Node.js

On my server file system I have a directory which contains some .bin file filled with 16 bit integers. How can I load a Uint16Array variable with the content of a specific .bin file in Node.js?

I already tried:

var arrayFromBinFile = new Uint16Array('./myDirectoryContainingBinFiles/selectedFile.bin')

By using console.log in node.js all I get is:

{ BYTES_PER_ELEMENT: 2,

get: [Function: get],

set: [Function: set],

slice: [Function: slice],

subarray: [Function: subarray],

buffer: { slice: [Function: slice], byteLength: 0 },

length: 0,

byteOffset: 0,

byteLength: 0 }


Convert nested 'for' loops into a Promise, for a Promise? Nested Promises?

I have an array where the values are sequences separated by '/', and a 'mapSeries' Promise (helper function for serially iteration with mapping) that loops through each value within each of the sequences.


Right now, the statement starts with a nested 'for' loop that splits a sequence into strings, and then pushes these values to an empty array to hand off to the 'mapSeries' promise..


After testing, it turns out that this only works if the original array has one sequence because multiple sequences run in parallel.


How can this be written as a promise that runs serially for each sequence, and then serially for each element in the given sequence?


Here's the attempt at the for loop (works for a single sequence):



var sequences = ['one/two/three', 'alpha/beta'];
var elements = [];
for (i=0; i<sequences.length; i++) {
var series = sequences[i].split("/");
for (j=0; j<series.length; j++) {
elements.push(series[j]);
}
var items = mapSeries(elements, function(element) {
// do stuff with 'one', then 'two', then 'three'
// when done..next series
// do stuff with 'alpha', then 'beta'
})
elements = []; // reset elements array for next series
} // for sequences.length


And here's an attempt at a Promise (error at element.charAt..):



var sequences = ['one/two/three', 'alpha/beta'];
var elements = [];
var items = mapSeries(sequences, function(sequence) {
sequence = sequence.split("/");
return mapSeries(sequence, function(series) {
elements.push(series);
return elements;
}).then(function(elements) {
return mapSeries(elements, function(element){
var element = element.charAt(0).toLowerCase() + element.slice(1); // first letter lowercase
// do stuff with 'one', then 'two', then 'three'
// when done..next series
// do stuff with 'alpha', then 'beta'
});
});
elements = []; // reset elements array for next series
});


mapSeries helper function:



function mapSeries(things, fn) {
var results = [];
return Promise.each(things, function(value, index, length) {
var ret = fn(value, index, length);
results.push(ret);
return ret;
}).thenReturn(results).all();
}

npm bcrypt wont install in EC2 bootstrap script

So I am trying to install npm packages via AWS ec2 bootstrap script. Works fine generally, but for some reason bcrypt wont install. All other packages install fine.


If I ssh into the machine, I can see bcrypt didn't get installed, but I can manually install bcrypt via:



npm install bcrypt


I execute the exact same command in the bootstrapping script. Is there some reason why bcypt can't be installed outside of an interactive console?


Create window-like menu on OS X

I'd like to create a same sort of tray menu like this application. Because it is on the list of applications that use node-webkit/nw.js, I think it's possible. I have looked through all the documentation and couldn't find anything on how to achieve that. Searching Google also wasn't really fruitful.


Maybe one of you guys has done this before and could send me in the right direction?


Loopback IO OAuth not working

I am trying to get a https loopback server up and running protected by OAuth. I am using the loopback gateway sample project as a reference. But for some reason I can't get the OAuth piece to work. What I mean is, even after adding in the OAuth bits and pieces, the APIs don't seem to be protected. I get a response back even if there is no token in my request. This is what my server.js looks like





var loopback = require('loopback');
var boot = require('loopback-boot');


var https = require('https');
var path = require('path');
var httpsRedirect = require('./middleware/https-redirect');
var site = require('./site');
var sslConfig = require('./ssl-config');

var options = {
key: sslConfig.privateKey,
cert: sslConfig.certificate
};

var app = module.exports = loopback();

// Set up the /favicon.ico
app.middleware('initial', loopback.favicon());

// request pre-processing middleware
app.middleware('initial', loopback.compress());

app.middleware('session', loopback.session({ saveUninitialized: true,
resave: true, secret: 'keyboard cat' }));

// -- Add your pre-processing middleware here --

// boot scripts mount components like REST API
boot(app, __dirname);

// Redirect http requests to https
var httpsPort = app.get('https-port');
app.middleware('routes', httpsRedirect({httpsPort: httpsPort}));

var oauth2 = require('loopback-component-oauth2')(
app, {
// Data source for oAuth2 metadata persistence
dataSource: app.dataSources.pg,
loginPage: '/login', // The login page url
loginPath: '/login' // The login processing url
});

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// Set up login/logout forms
app.get('/login', site.loginForm);

app.get('/logout', site.logout);
app.get('/account', site.account);
app.get('/callback', site.callbackPage);

var auth = oauth2.authenticate({session: false, scope: 'demo'});
app.use(['/protected', '/api', '/me', '/_internal'], auth);

app.get('/me', function(req, res) {
// req.authInfo is set using the `info` argument supplied by
// `BearerStrategy`. It is typically used to indicate scope of the token,
// and used in access control checks. For illustrative purposes, this
// example simply returns the scope in the response.
res.json({ 'user_id': req.user.id, name: req.user.username,
accessToken: req.authInfo.accessToken });
});

signupTestUserAndApp();

//var rateLimiting = require('./middleware/rate-limiting');
//app.middleware('routes:after', rateLimiting({limit: 100, interval: 60000}));

//var proxy = require('./middleware/proxy');
//var proxyOptions = require('./middleware/proxy/config.json');
//app.middleware('routes:after', proxy(proxyOptions));

app.middleware('files',
loopback.static(path.join(__dirname, '../client/public')));
app.middleware('files', '/admin',
loopback.static(path.join(__dirname, '../client/admin')));

// Requests that get this far won't be handled
// by any middleware. Convert them into a 404 error
// that will be handled later down the chain.
app.middleware('final', loopback.urlNotFound());

// The ultimate error handler.
app.middleware('final', loopback.errorHandler());

app.start = function(httpOnly) {

if(httpOnly === undefined) {
httpOnly = process.env.HTTP;
}
server = https.createServer(options, app);

server.listen(app.get('port'), function() {
var baseUrl = (httpOnly? 'http://' : 'https://') + app.get('host') + ':' + app.get('port');
app.emit('started', baseUrl);
console.log('LoopBack server listening @ %s%s', baseUrl, '/');
});
return server;};

// start the server if `$ node server.js`
if (require.main === module) {
app.start();
}

function signupTestUserAndApp() {
// Create a dummy user and client app
app.models.User.create({username: 'bob',
password: 'secret',
email: 'foo@bar.com'}, function(err, user) {

if (!err) {
console.log('User registered: username=%s password=%s',
user.username, 'secret');
}

// Hack to set the app id to a fixed value so that we don't have to change
// the client settings
app.models.Application.beforeSave = function(next) {
this.id = 123;
this.restApiKey = 'secret';
next();
};

app.models.Application.register(
user.username,
'demo-app',
{
publicKey: sslConfig.certificate
},
function(err, demo) {
if (err) {
console.error(err);
} else {
console.log('Client application registered: id=%s key=%s',
demo.id, demo.restApiKey);
}
}
);

});
}



I don't get any errors when the server starts up. Thoughts?


How to use coffescript with uglify in gulp?

I have following project structure



assets
--javascripts
----controllers
------somefile.js
------somefile.js.coffee


and I would like to compile coffescripts files (*.js.coffee) then concat all the files and then minify them.



var gulp = require('gulp')

var concat = require('gulp-concat')
var coffee = require('gulp-coffee');
var uglify = require('gulp-uglify')
var gulpFilter = require('gulp-filter');

gulp.task('scripts', function() {
var coffeeScriptFilesFilter = gulpFilter(['*.js.coffee']);

return gulp.src(['assets/javascripts/**/*'])
.pipe(coffeeScriptFilesFilter)
.pipe(coffee())
.pipe(coffeeScriptFilesFilter.restore())
.pipe(concat('application.js'))

.pipe(gulp.dest('public'))
.pipe(uglify().on('error', errorHandler));

function errorHandler (error) {
console.log(error.toString());
this.emit('end');
}
});


Unfortunately I am getting this error



Error in plugin 'gulp-uglify'
Message:
/var/www/gulp/public/application.js: Unexpected token: operator (>)
Details:
fileName: /var/www/gulp/public/application.js
lineNumber: 3


Without uglify plugin everything works fine. The results is



console.log('hello!');
var lol = 'asd!';
(function() {
var test;

test = function() {
return "lol";
};

}).call(this);


The uglify plugin probably is trying to compress .js.coffee file but I do not know exactly why. How can I fix it?