EzDevInfo.com

actionhero

actionhero.js is a multi-transport nodejs API Server with integrated cluster capabilities and delayed tasks actionhero.js - Home actionhero.js is a multi-transport framework node.js api server with integrated cluster capabilities and delayed tasks

how to execute a command line in node.js?

I am using the actionhero framework, it can be started by command actionhero start. but the problem is that, my cloud node.js app runner can only run an app by specify a main file, such as index.js. How can I adapt my app to be started by a normal node.js file?


Source: (StackOverflow)

How to set Environment variables from within package.json [Node.js]

How to set some Environment variables from within package.json to be used with npm start like commands

here is what i want to achieve.

package.json

{
  ...
  "scripts": {
    "help": "actionhero help",
    "start": "actionhero start",
    "startCluster": "actionhero startCluster --workers=1",
    "actionhero": "actionhero"
  }
  ...
}

here i want to set Environment variables (like NODE_ENV and others) in start script section, and i want to start app with just one command, npm start.


Source: (StackOverflow)

Advertisements

Node.js + Actionhero code not runnign consecutively

I'm obviously missing something very important about how Node.js and Actionhero work.

Can someone please explain to me why the following problem occurs:

I have this simple code: Basically it reads a .css file .

buildAdsHTML: function (ads, type) {
        var cssDir = path.normalize(__dirname + '/../public/css/');
        switch (type) {
            case  'text':
                var result = '';
                console.log("STEP 1");
                fs.readFile(cssDir + type + 'Ads.css', {encoding: 'utf8'}, function (err, data) {

                    console.log(err);
                    console.log(data);
                    if (!err) {

                        console.log("STEP 2");
                        result += '<style>' + data + '</style>';


                    } else {

                    }
                });

                break;


        }
        console.log('STEP 3');
        return result;
    }

Now when this code is run i get an empty string as result. The console output is the following:

STEP 1 <- so far so good 
STEP 3<- this should be last!

null <- this is the error variable 

.some-random-css-class{
    display: block;
    width: 100;
    min-height: 250px;
}

STEP 2

Now at some point i figured out that that fs.reafFile is async function. So I naturaly changed it to the sync version fs.readFileSync. Now the console output is even worse:

STEP 1
STEP 3

Thats it ! Nothing else. And i still get a empty string as result. Like the whole code isnt even going through the swich.

I've noticed this behavior in all functions and methods of my actionhero project, most notebly when calling next(connection). You cant just call it at the end of the method.

For every if or swich I have to call it inside to have any actual control over the result.

Otherwise every new data i've added to the connection is lost.

Whats with that ? Please explain that functionality in detail so I dont make any dumn mistakes while coding.

Thank you .


Source: (StackOverflow)

Assigning middlewares to specific actions in ActionHero

Is the anyway to add some middleware to specific actions? because as far as I know addPreProcessor adds the middleware to all the actions? lets say you don't want to have authentication or some other checks on some actions, is there any solution?

I have a short term solution but it would be nice if you could assign your specific middlewares when you're defining your action(like giving an array of middleware names that need to be run, in order)

My current solution is keeping an array of all the actions that I need to apply the middleware to them and then check it against the connection.aciton, but then still every single request goes through all the middlewares and then it gets passed around which it doesn't sound efficient to me!

exports.middlewares = function(api, next){

    var myImportantMiddleware = function(connection, actionTemplate, next) {

        var actionsToBeChecked = ['deposit'];
        var action = connection.action;

        if(actionsToBeChecked.indexOf(action) > -1) {
                /*  middleware logic 
                next(connection, true); */
        } else {
            next(connection, true);
        }
    }

    api.actions.addPreProcessor(myImportantMiddleware);

    next();
}

Thanks in advance !


Source: (StackOverflow)

When sequelize.import model, the tablename appear to have a extra 's' at the end

I use actionhero + sequelize plus mysql. When I do this

var sequelize = new Sequelize("MJN", "testUser", "testPasss", {
            "host": "192.168.123.321",
            "dialect": "mysql",
            "port": 3306,
            "pool": {
                "maxConnections": 20,
                "maxIdleTime": 30000
            }
});

var MJNCustomer = sequelize.import(__dirname + "/../models/MJNCustomer.js");

I do console.log(MJNCustomer.tableName);, and it return MJNCustomers instead of MJNCustomer.

Here is models/MJNCustomer.js

module.exports = function(sequelize, DataTypes) {
return sequelize.define('MJNCustomer', {
    customerId:         DataTypes.STRING,
    fname:              DataTypes.STRING,
    lname:              DataTypes.STRING,
    address1:           DataTypes.STRING,
    address2:           DataTypes.STRING,
    city:               DataTypes.STRING,
    phoneNumber:        DataTypes.STRING
});

}

what did I do wrong here?


Source: (StackOverflow)

nodejs actionhero download picture file trouble

I'm building simple image file upload/download server and I'm following this wiki page . In this part I'm passing the xpath parameter which is the file name and it all works fine for text files but I'm getting 404 when trying the same for images.

  renderFile: function(api, connection, next){
    // do any pre-rendering etc here
    connection.rawConnection.responseHttpCode = 200;
    connection.sendFile(connection.params.xpath);
    next(connection, false);
  },

  run: function(api, connection, next){
    var self = this;
    if(connection.params.xpath == null){
      self.render404(api, connection, next);
    }else {
      var file = api.config.general.paths.public + '/' + connection.params.xpath
      console.log(file);
      fs.exists(file, function(found){
        if(found){
          self.renderFile(api, connection, next);
        }else {
          self.render404(api, connection, next);
        }
      });
    }
  }

is there any settings or config I missed?


Source: (StackOverflow)

ActionHero js and custom websocket event

I am trying to use the websockets implementation of ActionHero.js. Looking at the documentation it's clear how to implement a chat, but I don't understand how is possible to emit a custom event from server to client and organizing a complex realtime app. I am looking at the primus-emitter project examples: https://github.com/cayasso/primus-emitter

Anybody knows? Thanks


Source: (StackOverflow)

What would cause a Javascript object to have the properties of the object that it replaced?

TLDR;

$scope.newEvent is filled by a form.

$scope.addEvent sends $scope.newEvent to the server, then replaces it with an empty object. First submission works flawlessly, additional submissions have the last value of any properties that have been submitted before, even though the object does not have those properties:

First Submission

Client        Server
{             {
  a:1,          a:1, 
  b:2,          b:2,
  c:3           c:3
}             }

Second Submission

Client        Server
{             {
  a:3           a:3,
}               b:2,
                c:3
              }

The client consistently insists that the property only contains what is filled out in the form, even after the form has been submitted.

I feel like most likely this happening because of some Javascript feature/quirk that I am unaware of, and might be very easy, if I just knew hat I was looking for...

Background:

I am working on a project that uses Angular and Actionhero. I've searched all over for the answer to this and haven't found anything, but then again, I don't really know what to call it...

  • AngularJS is the front end framework.
  • Actionhero is a http/websockets/sockets API framework.
  • Nexus is the Angular factory that I am working on. There are 2 versions, and both are showing the same symptoms. The current version is working but incomplete, and is a ground up rewrite of the old version.

I am trying to create an Angular factory that will connect to Actionhero, parse a list of available actions, and allow you to request data, and have it kept up to date, without having to do anything.

I have a working service, and everything seems to works great... I have an Angular controller with a function to send some data to an Actionhero, and the first time it runs everything is great and the data is sent properly.

However any time after the first, any properties that aren't sent, that have been sent before, are filled with the previous values! Oddly enough, this still happens even after the controller is destroyed, until the page is refreshed...

What I do know, is that if this function is replaced with a call to $http it works flawlessly, so I am kind of leaning to an error in the Nexus factory... BUT you can log the parameters at any point in the factory, including before and after the data is sent, and it is always correct, even though it shows as being posted with extra data on the server...

// Initialize the Nexus client
var nexus = $nexus($scope);

// ...

// Add an event when a button is clicked.
var $scope.addEvent = function (){

    // Post data from $scope.newEvent to the event_create action
    nexus.action('event_create', 1, $scope.newEvent)
    .then(function(response){

        // $scope.newEvent is a form that gets filled in
        // Logging $scope.newEvent always gives exactly what was in the form.
        // Here it gets replaced with a new, empty object, to clear the form
        $scope.newEvent = {};

        // Displays a banner saying that you creation was successful and gives you a link.
        var event_id = response.data.id;
        $('#event-success-alert').show();
        $('#event-options').hide();
        $('form[name="add-event"]').trigger('reset');
        $('#new-event-link').attr('href','#/app/event/' + event_id);
    })
    .error(function(err){
        console.log(err);
    });
};

I am fairly new to some of the more advanced Javascript concepts that I am using for this project, so any suggestions/comments on any part of it are very welcome. Also, if any of you need to see it working to get a better idea, just let me know, and I can schedule something with you. (It's not publically available.)


Source: (StackOverflow)

ActionHero js with Mongoose

I am creating some rest API with ActionHero js and Mongoose. I put the Mongoose code in an initalizers and everything works. When I modify some files the project automatically recompiles and it returns the following error: OverwriteModelError:

Cannot overwrite User model once compiled.

How should I edit my code to avoid this error? 'use strict';

var mongoose   = require('mongoose');


exports.mongo = function(api, next) {

    mongoose.connect(api.config.mongo.host);

    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function callback () {
        console.log('Connection opened');
    });

    var Schema = mongoose.Schema,
        Types = mongoose.Schema.Types;

    var userSchema = mongoose.Schema({
        createdAt: { type: Date, default: Date.now(), required: true},
        updatedAt: { type: Date, required: false},
        email: { type: String, required: true },
        name: { type: String, required: true },
        surname: { type: String, required: true },
        password: { type: String, required: true },
        roles: [],
        tokens: [{
            code: String,
            expiryDate: { type: Date, default: Date.now() + 30 }
        }]
    });


    var User = mongoose.model('User', userSchema);

    var postSchema = mongoose.Schema({
        createdAt: { type: Date, default: Date.now(), required: true},
        updatedAt: { type: Date, required: false},
        content: { type: String, required: true },
        votes: { type: [Types.ObjectId], ref: 'User' } ,
        coordinates: { type: [Number], index: { type: '2dsphere' }, required: true },
        creator: { type: Schema.Types.ObjectId, ref: 'User', required: true }
    });


    var Post = mongoose.model('Post', postSchema);

    api.mongo = {
        mongoose: mongoose,
        user: User,
        post: Post
    };

    next();
};

Source: (StackOverflow)

ActionHero js and header field token not allowed

I am doing a fronted app that interacts with ActionHero js rest api. I am trying to pass a token string in the header from client to server. In Angular.js I use this method to add the token to every request:

$http.defaults.headers.common['token'] = token;

However Chrome stops me with this message:

XMLHttpRequest cannot load
http://localhost:8080/api/users/310d35173186997379296ab827ffe433.
Request header field token is not allowed by
Access-Control-Allow-Headers.

If I call the resource with a generic rest client everything works fine. I did some research but I can't really understand the problem here.

...

Problem solved, I missed the allowed headers in ActionHero configuration file web.js

httpHeaders : {
      'X-Powered-By'                : api.config.general.serverName,
      'Access-Control-Allow-Origin' : '*',
      'Access-Control-Allow-Methods': 'HEAD, GET, POST, PUT, DELETE, OPTIONS, TRACE',
      'Access-Control-Allow-Headers': 'Content-Type, token'
},

Source: (StackOverflow)

NSstream write encoding issues

Im trying to send a string using NSoutputstream , however i cant seem to get the encoding right , using dataWithContentsOfURL works

im using a nodejs TCP server with actionHero library.

it works using netcat and telnet.

- (IBAction)sendText:(id)sender {
NSString *response  = [NSString stringWithFormat:@"%@", [_sendTextField.text stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
NSLog(@"writing %@",response);

///////////////////////////// this line works/////////////////////////////////////////////////////
//  NSData *data = [[NSData alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL   URLWithString:@"http://www.google.com"]]];


///////////////////////////// this line doesnt work/////////////////////////////////////////////////////
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSUTF8StringEncoding]];


//%u returns a non zero value
NSLog(@"%u",[outputStream write:[data bytes] maxLength:[data length]]);
}

i get a null streamError from handle stream Event method


Source: (StackOverflow)

actionHero.js Set Http Header

I want to know if there is a way to Set the Http.Header in actionHero.js: in our server we are working with actionHero.js and Golang I need to send on the "Header" two domain name "client domain & mine(actionHero Service)" to the Golang service. or if there is any other way to do it on the Proxy server

thank you in advance


Source: (StackOverflow)