Expressjs, Handlebars(hbs), express-messages, flash-connect. Not able to render flash messages

I’m doing an express app and I’d like to show flash messages when a user registers using a form.

The technologies that I’m using are Node.js, Express.js, Handlebars(hbs), connect-flash and express-messages.

In order to be easier to find the error, I’ve created a new app in the simplest way that I could.

The error is:
Error: /Applications/MAMP/htdocs/hbs-simple/views/index.hbs: Parse error on line 7:
...</head><body> {{{messages()}}} {{{b
---------------------^
Expecting 'ID', 'STRING', 'NUMBER', 'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', got 'INVALID'

Project structure:

├── app.js
├── package.json
└── _views
    ├── index.hbs
    ├── layout.hbs
    └── test.hbs

app.js:

const express = require('express');
const app = express();
const path = require('path');
const session = require('express-session');
const flash = require('connect-flash');
const hbs = require('hbs');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(require('connect-flash')());
app.use((req, res, next) => {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

// Handle Sessions
app.use(session({
  secret: 'secret',
  saveUninitialized: true,
  resave: true
}));

app.get('/', (req, res, next) => {
  req.flash('success', 'Rendering index...');
  res.render('index');
});

app.get('/test', (req, res, next) => {
  req.flash('success', 'Rendering test...');
  res.render('test');
});

app.listen(3000, function () {
  console.log('Listening on port 3000!');
});

layout.hbs

<!DOCTYPE html>
<html>
<head>
  <title>{{title}}</title>
</head>
<body>
  {{{messages()}}}
  {{{body}}}
  <a href="/">index</a>
  <a href="/test">test</a>
</body>
</html>

index.hbs

<h3>This is the index</h3>

test.hbs

<h3>This is the index</h3>

package.json

{
  "name": "hbs-simple",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "Rafa",
  "license": "ISC",
  "dependencies": {
    "connect-flash": "^0.1.1",
    "express": "^4.15.3",
    "express-messages": "^1.0.1",
    "express-session": "^1.15.3",
    "hbs": "^4.0.1",
    "path": "^0.12.7"
  }
}

This is from the express-messages documentation that you can find on [https://github.com/expressjs/express-messages][1]

Rendering Messages

Call the messages() function as specified by your rendering engine:

EJS:

<%- messages() %>
Jade:

!= messages()

Which using hbs should be {{{messages}}} , but this doesnt work as I expected.

Any ideas or any solution for this situation.

Thanks a lot!


Source: stackoverflow-javascript

Using promises with streams in node.js

I’ve refactored a simple utility to use promises. It fetches a pdf from the web and saves it to disk. It should then open the file in a pdf viewer once saved to disk. The file appears on disk and is valid, the shell command opens the OSX Preview application, but a dialog pops up complaining that the file is empty.

What’s the best way to execute the shell function once the filestream has been written to disk?

// download a pdf and save to disk
// open pdf in osx preview for example
download_pdf()
  .then(function(path) {
    shell.exec('open ' + path).code !== 0);
  });

function download_pdf() {
  const path = '/local/some.pdf';
  const url = 'http://somewebsite/some.pdf';
  const stream = request(url);
  const write = stream.pipe(fs.createWriteStream(path))
  return streamToPromise(stream);
}

function streamToPromise(stream) {
  return new Promise(function(resolve, reject) {
    // resolve with location of saved file
    stream.on("end", resolve(stream.dests[0].path));
    stream.on("error", reject);
  })
}


Source: stackoverflow-javascript

How to get stdout data back and forth from child process in Node.js

I’m running a command in node.js using child_process.spawn.
This command has an interactive mode, so that can get the stdin to take input from the console and output results to stdout. I’m using this mode, to send commands to this child via the child.stdin.write( data+'rn' );.

  • I suppose to get the results in the callback child.stdout.on('data'),
    but it seems I’m not getting all data wrote by the command, that I can see in the bash stdout output, but not in the callback.

  • I would like a way to retrieve the data sent with child.stdin.write(
    data+'rn' );
    in order to get the tuple/struct (data,result), since
    the execution is asynchronous.

For convenience, I have added a callback for the child.stdout.on('data') to get results outside that scope.
My code looks like:

    var exec = function(name,command,params,options,callback) {
    var self=this;

    /** default ChildProcess options
     * @see https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options
    */
    var _options = {
        // Prepare child to run independently of its parent process
        //detached: true
    };
    for (var attrname in options) { _options[attrname] = options[attrname]; }

    var created_time= ( new Date() ).toISOString();
    var task = require('child_process').spawn(command, params, _options);
    task.stdout.on('data', function(result) {
        var out=new Buffer(result,'utf-8').toString();
        callback(out);
    });
    task.on('error', function(error) {
        if(self.logger) self.logger.error("exec:%s pid:%d error:n%@",name,task.pid,error);
    });
    task.on('uncaughtException', function (error) {
        if(self.logger) self.logger.error("exec:%s pid:%s uncaughtException:n%@",name,task.pid,error);
    });
    task.stdout.on('end', function(data) {
        if(self.logger) self.logger.debug("exec:%s end.",name);
    });
    task.stderr.on('data', function(data) {
        if(self.logger) self.logger.debug("exec:%s stderr:%s",name,data);
    });
    task.on('close', (code, signal) => {
        if(self.logger) self.logger.warn('task:%s pid:%s terminated due to receipt of signal:%s',name,task.pid,signal);
    });
    task.on('exit', function(code) {
        if(self.logger) self.logger.debug("exec:%s exit.",name);
        if (code != 0) {
            var error=new Error();
            error.description= command + ' ' + params.join(' ');
            error.code=code;
            if(self.logger) self.logger.error("exec:%s pid:%d error:n%@",name,task.pid,error);
        }
        // at exit explicitly kill exited task
        task.kill('SIGINT');
    });
    return task;
}//exec

// load child task
var load = function(model,callback) {
    var m=exec('fasttext','./fasttext', ['predict', model, '-'], {}, callback);
    m.stdout.pipe(process.stdout);
    return m;
}//load

// send data to child task
var send = function(task,data) {
    task.stdin.setEncoding('utf-8');
    task.stdin.write( data );
    task.stdin.write('rn');
}//send

I run the command like

var model=load(modelFile,
function(result) {
    console.log(result);
});
send(model,result);

NOTE.

In this specific case the command was fasttext a command line classification utility by Facebook Inc., that can run in interactive mode when called like ./fasttext predict filePath -.


Source: stackoverflow-javascript

Livereload reloads only the first .css file in head

I am setting up Livereload in a Node environment, using Express server and Gulp as my task runner and, finally, using Ejs for my templates.

The issue: I am not able to get all .css reloaded. I only get the first .css file in head bound to the livereload server.

Current set up:

I installed livereload package, and set it up in my index.js file like:

// ...
// index.js

var lr = require('livereload');
var lrServer = lr.createServer();
lrServer.watch(__dirname + '/public');

Note: Right now, all my files are in /public folder. Later I will set them up to a /dist folder.

The express set up is a very basic set up.

// ...
// index.js
//
// ================================================
// Ejs for my templates/partials
// ================================================
app.engine('.ejs', require('ejs').__express);
app.set('view engine', 'ejs');

// ================================================    
// static files from my currently set static folder
// ================================================
app.use(express.static(path.join(__dirname + '/public')));

// ================================================    
// Express starting on :3000 + istanbul ignore next
// ================================================
if (!module.parent) {
    var port = 3000;
    app.listen(port);
    console.log('Express started on port', port);
}

Finally, I start my server with nodemon

"#file": "package.json",
...
"scripts": {
    "start": "nodemon -e js,ejs --watch views index.js",
},
...

If everything should be fine, is there an alternative way, without using livereload plugin, to get a Node/Express/Ejs/Gulp environment working with Livereload?

Thank you all for you help.


Source: stackoverflow-javascript

Why is node giving me this error?

i’ve been trying to make my first twitter bot, but when I run npm run dev I get this error:

> Tweeter@1.0.0 dev /mnt/c/Users/rfasc/Dropbox/Hackathon/HackCuTwitter
> node app.js

npm ERR! weird error 1
npm WARN This failure might be due to the use of legacy binary "node"
npm WARN For further explanations, please read
/usr/share/doc/nodejs/README.Debian

npm ERR! not ok code 0 

am somewhat new to using nodejs and the npm commmands to connect my code. Here is my package.json and my app.js file:

package.json:

{
  "name": "Tweeter",
  "version": "1.0.0",
  "description": "package.json tester",
  "main": "app.js",
  "dependencies": {
    "twitter": "^1.7.0",
    "twitter-stream-api": "^0.5.1"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "dev": "node app.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/kennychiwa/HackCuTwitter.git"
  },
  "author": "",
  "license": "BSD-2-Clause",
  "bugs": {
     "url": "https://github.com/kennychiwa/HackCuTwitter/issues"
  },
  "homepage": "https://github.com/kennychiwa/HackCuTwitter#readme"
}

and app.js:

var twitterpack = require('twitter');

var tokens {
  consumer_key: '-------9WJSaaqAe9yVvr30CF',
  consumer_secret: '-------------------fj3zoiZ2nUOTBWUjP4DqtGXIlzzbxbOY',
  token_key: '  ----------zNHmdL43N6RZJeOtJeH8ZhrursJUQlAqCycHqxbl',
  tokenk_secre: '----EcxAjUq1hLka2QYwSSZStETF7Mr2mBikHYCTTqodV'
}
var twitter = new twitterpack(tokens);

Twitter.stream('statuses/filter', {track: 'hey'}, function(stream) {

  stream.on('data', function(stream){

    console.log(tweet.text);
    var meanReply = {status: "hey @" + tweet.user.screen_name}
    Twitter.post('statuses/update', meanReply, function(error, tweetReply, 
response){
      if(error) {console.log(error) /*&&db.collection('errors', 
error.text)*/};
      console.log(tweetReply.text)}
     );


  });
   stream.on('error', function(error) {
   console.log(error);
  });
});

please help, thanks.


Source: stackoverflow-javascript

node.js addon call javascript function failed

I want to call a javascript function(which is in the test.js) from my C++ addon by name but not pass it as an argument in the FunctionCallbackInfo<Value> object. Version of my node.js is 6.10.2.

test.js:

function callme(msg)
{
    console.log(msg);
}
const addon = require('./build/Debug/addon11');
addon.StartRun();

addon.cc:

#include<node.h>

namespace demo
{
    using v8::FunctionCallbackInfo;
    using v8::Isolate;
    using v8::Local;
    using v8::Object;
    using v8::String;
    using v8::Value;
    using v8::Exception;
    using v8::Function;
    using v8::Context;
    using v8::HandleScope;
    using v8::MaybeLocal;

    void Method(const FunctionCallbackInfo<Value>& args)
    {
        Isolate* isolate = Isolate::GetCurrent();
        HandleScope scope(isolate);
        Local<Context> context = isolate->GetCurrentContext();
        Local<Object> global = context->Global();
        if (global.IsEmpty() || global->IsNull())
        {
            return;
        }
        MaybeLocal<Value> mbValue = global->Get(String::NewFromUtf8(isolate, "callme"));
        if (mbValue.IsEmpty())
        {
            isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, "can't find the function callme!")));
            return;
        }
        Local<Value> vTmp = mbValue.ToLocalChecked();
        if (!vTmp->IsFunction())
        {
            return;//it will retun here
        }
        Local<Function> callFunc = Local<Function>::Cast(vTmp);
        Local<Value> argv[] = { String::NewFromUtf8(isolate, "call from c++") };
        callFunc->Call(Null(isolate), 1, argv);
    }

    void init(Local<Object> exports)
    {
        NODE_SET_METHOD(exports, "StartRun", Method);
    }

    NODE_MODULE(addon11, init)
}

when I debug the code it returns here:

        Local<Value> vTmp = mbValue.ToLocalChecked();
        if (!vTmp->IsFunction())
        {
            return;//it will retun here
        }


Source: stackoverflow-javascript

Don’t call grecaptcha.render to render again if it is rendered allready

I have a login dialog with three buttons. “skip”, “login”, “signup”. I use invisible recaptcha to detect if robots click on them. the thing is if I click login and I get sent back an error message like “username is not in DB” and I click login again to try again, I get an error

Uncaught Error: ReCAPTCHA placeholder element must be empty

I think it is because I do the render on every time the button get clicked.

Is there a way to set it it up so I could tell if the badge is rendered or not so I could tell it to render.

I do something like this in click handler:

    if($(this).attr("id") == "login"){
        var login =  grecaptcha.render("login", {"sitekey": "6Le_shsUAAAAAKd8foacccmK6Y635DlIBvX4BQY" , "callback" : verifyCallback, "size" : "invisible"})

        grecaptcha.execute(login);
        console.log(grecaptcha.getResponse(login));

    }else if($(this).attr("id") == "signup"){
        var signup =  grecaptcha.render("signup", {"sitekey": "6Le_shsUAAAAAKdccccK6Y635DlIBvX4BQY" , "callback" : verifyCallback, "size" : "invisible"})

        grecaptcha.execute(signup);
        console.log(grecaptcha.getResponse(signup));
    }


})

I can’t just get the css selector of the badge because it doesn’t associate it to the button.


Source: stackoverflow-javascript

RxJS Observable with asynchronous subscriber function

I’m trying to do something that feels like it should be straightforward, but is proving surprisingly difficult.

I have a function to subscribe to a RabbitMQ queue. Concretely, this is the Channel.consume function here: http://www.squaremobius.net/amqp.node/channel_api.html#channel_consume

It returns a promise which is resolved with a subscription id – which is needed to unsubscribe later – and also has a callback argument to invoke when messages are pulled off the queue.

When I want to unsubscribe from the queue, I’d need to cancel the consumer using the Channel.cancel function here: http://www.squaremobius.net/amqp.node/channel_api.html#channel_cancel. This takes the previously returned subscription id.

I want to wrap all of this stuff in an Observable that subscribes to the queue when the observable is subscribed to, and cancels the subscription when the observable is unsubscribed from. However, this is proving somewhat hard due to the ‘double-asynchronous’ nature of the calls (I mean to say that they have both a callback AND return a promise).

Ideally, the code I’d like to be able to write is:

return new Rx.Observable(async (subscriber) => {
  var consumeResult = await channel.consume(queueName, (message) => subscriber.next(message));
  return async () => {
    await channel.cancel(consumeResult.consumerTag);
  };
});

However, this isn’t possible as this constructor doesn’t support async subscriber functions or teardown logic.

I’ve not been able to figure this one out. Am I missing something here? Why is this so hard?

Cheers,
Alex


Source: stackoverflow-javascript

Node throw new Error(‘Can’t set headers after they are sent.’)

I am having the above problem with one of my node calls.
To my knowledge this error shows if you res.send gets called more than once.
Looking at the code it should only send res once so I am not sure what is wrong here.

It throws the error when I insert

        else {
            res.send("Username or Password is wrong");

        }




var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var cors = require('cors');
var massive = require('massive');
var config = require('./config');
var app = express();

app.use(bodyParser.json());
app.use(cors());

var db = massive.connect({connectionString: config.connectionString}, function(err, localdb){
    db = localdb;
    app.set('db', db);

});

app.post('/api/login', function(req, res, next) {

    db.get_users(function(err, users) {
        if(err) res.status(500).json(err);
        else {
            for(var i = 0; i < users.length; i++) {
                if(req.body.email == users[i].email && req.body.password == users[i].password) {
                    console.log("matched");

                    var currentUser = users[i];
                    res.send({
                        msg: 'passed',
                        user: currentUser
                    })
                }
                else {
                    res.send("Username or Password is wrong");

                }
            }
        }

    })
})

app.listen(3000, function() {
    console.log("I am listening");
})


Source: stackoverflow-javascript