How to add DockerEvents to my Javascript - javascript

I'm using Dockerode and now I want to implement a listener so I have founded docker-events but when I want to use it I got this error :
ReferenceError: DockerEvents is not defined
My code look like this :
if (Meteor.isServer) {
//publish the collection
Meteor.publish('infosContainers', function readInfosContainers() {
return InfosContainers.find({});
});
}
Meteor.startup(() => {
console.log("startup server");
//at the start I create the docker object
docker = new Docker({socketPath: '/var/run/docker.sock'});
//create the docker events
emitter = new DockerEvents({
docker: new Dockerode(docker),
});
//maybe I need to create it like this
emitter = new DockerEvents(docker);
//start the emitter
emitter.start();
});
/**
* this method listen if a container Start
**/
emitter.on("start", function(message) {
console.log("container started: %j", message);
});
Someone know what I'm doing wrong ? Thank you for the help

The error means that you are trying to access a variable that doesn't exist, i.e. you don't have var DockerEvents = ...; anywhere.
I assume you load dockerode like this:
var Docker = require('dockerode');
If you want to use docker-events, you have to do the same:
var DockerEvents = require('docker-events');
require('modulename') is how you load modules in Node.js.
How to use docker-event is already described in its documentation:
var emitter = new DockerEvents({
docker: docker, // since you defined docker earlier
});

Related

Event Listener on particular document Id, not on whole database

How can I continuously listen on particular document of a database in couchdb? If anything changes only in that document, then and only then I want to console that document, otherwise not. How can I achieve that?
my db entry in couchdb:
{
"_id": "my-doc",
"_rev": "13-7cf9b1373542d93da7b484774856429d",
"awesome": "my-doc"
}
my code:
var
util = require('util'),
couchdb = require('felix-couchdb'),
client = couchdb.createClient(5984, 'localhost'),
db = client.db('lookup');
db.changesStream({id:"my-doc"}, function(err,success){
if(!err){
console.log(success)
}
})
this code generates an error
stream = new process.EventEmitter(),
^
TypeError: process.EventEmitter is not a constructor
at exports.Db.Db.changesStream (/home/xyz/Projects/practice/node_modules/felix-couchdb/lib/couchdb.js:676:14)
other than I have tried using libraries like :- couchdb-api, couchdb-change-events..
To listen to a single document changes, you must supply docs_ids=["$id"] where $id is the id you want to track.
It seems like EventEmitter is not available. Perhaps you're trying to run nano in the browser?
You can use db.changes like this:
const nano = require('nano')('http://localhost:5984')
const db = nano.use('foo');
const req = db.changesAsStream({
since: "now", feed: 'continuous', doc_ids: JSON.stringify(["my-doc", "doc_2"])
}).pipe(process.stdout);
I recommend using the db.follow API. It has more feature and it's more stable I think
const nano = require('nano')('http://localhost:5984')
const db = nano.use('foo');
const feed = db.follow({since: "now",filter:"_doc_ids",doc_ids:JSON.stringify(["my-doc","doc_2"])});
feed.on('change', (change) => {
console.log("change: ", change);
});
feed.follow();

How can I close the client-side JavaScript 'Hub' connection in SignalR?

I have followed this tutorial.
But there is no hint how to close the Websocket connection via the HubConnection class in signalr.js-file. The file is V1.0.4.
This solution does not resolve my problem because I am using the microsofts javascript-library.
Here ist the code:
var lHubConnection = null;
var Init = function () {
// create instance
lHubConnection = new signalR.lHubConnectionBuilder().withUrl("/chatHub").build();
// receive message
lHubConnection.on("ReceiveMessage", function (pMessage) {
// show message
console.log(JSON.parse(pMessage));
});
// [...]
};
// close websocket connection
var CloseConnection = function(){
if (lHubConnection !== null && lHubConnection.connection.connectionState === 1) {
// lHubConnection.invoke("?"); ???
}
};
Here is an console output of the lHubConnection instance:
According to Microsoft the JavaScript client contains a stop function.
https://learn.microsoft.com/en-us/javascript/api/%40aspnet/signalr/hubconnection?view=signalr-js-latest#stop
In addition, you can find the .stop()-Method in the prototype of the framework:

Model return values from another file not working with Sequelize.js

I have the following code that does not work currently.
var config = require('./libs/sequelize-lib.js');
var connection = config.getSequelizeConnection();//Choosing to not pass in variable this time since this should only run via script.
var models = config.setModels(connection);//Creates live references to the models.
//Alter table as needed but do NOT force the change. If an error occurs we will fix manually.
connection.sync({ alter: true, force: false }).then(function() {
models.users.create({
name: 'joe',
loggedIn: true
}).then( task => {
console.log("saved user!!!!!");
});
process.exit();//close the nodeJS Script
}).catch(function(error) {
console.log(error);
});
sequelize-lib.js
var Sequelize = require('sequelize');
exports.getSequelizeConnection = function(stage){
var argv = require('minimist')(process.argv.slice(2)); //If this file is being used in a script, this will attempt to get information from the argument stage passed if it exists
//Change connection settings based on stage variable. Assume localhost by default.
var dbname = argv['stage'] ? argv['stage']+"_db" : 'localdb';
var dbuser = argv['stage'] ? process.env.RDS_USERNAME : 'admin';
var dbpass = argv['stage'] ? process.env.RDS_PASSWORD : 'local123';
var dbhost = argv['stage'] ? "database-"+argv['stage']+".whatever.com" : 'localhost';
//If state variable used during require overide any arguments passed.
if(stage){
dbname = stage+"_db";
dbuser = process.env.RDS_USERNAME
dbpass = process.env.RDS_PASSWORD
dbhost = "database-"+stage+".whatever.com"
}
var connection = new Sequelize(dbname,dbuser,dbpass, {
dialect: 'mysql',
operatorsAliases: false, //This gets rid of a sequelize deprecated warning , refer https://github.com/sequelize/sequelize/issues/8417
host: dbhost
});
return connection;
}
exports.setModels = function(connection){
//Import all the known models for the project.
const fs = require('fs');
const dir = __dirname+'/../models';
var models = {}; //empty model object for adding model instances in file loop below.
//#JA - Wait until this function finishes ~ hence readdirSync vs regular readdir which is async
fs.readdirSync(dir).forEach(file => {
console.log(file);
//Split the .js part of the filename
var arr = file.split(".");
var name = arr[0].toLowerCase();
//Create a modle object using the filename as the reference without the .js pointing to a created sequelize instance of the file.
models[name] = connection.import(__dirname + "/../models/"+file);
})
//Showcase the final model.
console.log(models);
return models; //This returns a model with reference to the sequelize models
}
I can't get the create command to work however with this setup. My guess is the variables must not be passing through correctly somehow. I'm not sure what I'm doing wrong?
The create command definitely works because if in the sequelize-lib.js I modify the setModels function to this...
exports.setModels = function(connection){
//Import all the known models for the project.
const fs = require('fs');
const dir = __dirname+'/../models';
var models = {}; //empty model object for adding model instances in file loop below.
//#JA - Wait until this function finishes ~ hence readdirSync vs regular readdir which is async
fs.readdirSync(dir).forEach(file => {
console.log(file);
//Split the .js part of the filename
var arr = file.split(".");
var name = arr[0].toLowerCase();
//Create a modle object using the filename as the reference without the .js pointing to a created sequelize instance of the file.
models[name] = connection.import(__dirname + "/../models/"+file);
models[name].create({
"name":"joe",
"loggedIn":true
});
})
//Showcase the final model.
console.log(models);
return models; //This returns a model with reference to the sequelize models
}
Then it works and I see the item added to the database! (refer to proof image below)
Take note, I am simply running create on the variable at this point. What am I doing wrong where the model object is not passing between files correctly? Weird part is I don't get any errors thrown in the main file?? It's as if everything is defined but empty or something and the command is never run and nothing added to the database.
I tried this in the main file also and no luck.
models["users"].create({
name: 'joe',
loggedIn: true
}).then( task => {
console.log("saved user!!!!!");
});
The purpose of this all is to read models automatically from the model directory and create instances that are ready to go for every model, even if new one's are added in the future.
UPDATE::
So I did another test that was interesting, it seems that the create function won't work in the .then() function of the sync command. It looks like it was passing it correctly though. After changing the front page to this...
var config = require('./libs/sequelize-lib.js');
var connection = config.getSequelizeConnection();//Choosing to not pass in variable this time since this should only run via script.
var models = config.setModels(connection);//Creates live references to the models using connection previosly created.
models["users"].create({
"name":"joe",
"loggedIn":true
});
//Alter table as needed but do NOT force the change. If an error occurs we will fix manually.
connection.sync({ alter: true, force: false }).then(function() {
process.exit();//close the nodeJS Script
}).catch(function(error) {
console.log(error);
});
Doing this seems to get create to work. I'm not sure if this is good form or not though since the database might not be created at this point? I need a way to get it to work in the sync function.
Well I answered my question finally, but I'm not sure I like the answer.
var config = require('./libs/sequelize-lib.js');
var connection = config.getSequelizeConnection();//Choosing to not pass in variable this time since this should only run via script.
var models = config.setModels(connection);//Creates live references to the models using connection previosly created.
//Alter table as needed but do NOT force the change. If an error occurs we will fix manually.
connection.sync({ alter: false, force: false }).then( () => {
models["users"].create({
"name":"joe",
"loggedIn":true
}).then( user => {
console.log("finished, with user.name="+user.name);
process.exit();
}).catch( error => {
console.log("Error Occured");
console.log(error);
});
}).catch(function(error) {
console.log(error);
});
turns out that process.exit was triggering before create would occur because create happens async. This means that all my code will have to constantly be running through callbacks...which seems like a nightmare a bit. I wonder if there is a better way?

Node event emitter in other modules

I have 3 different javascript files, the smallest one is emitting an event, meanwhile the second (bigger one) file picks up the event and sends it further to the main file.
This is what I have tried so far:
//mini.js
var EventEmitter = require('events').EventEmitter;
var ee = new EventEmitter;
console.log("Emitting event");
var message = "Hello world";
ee.emit('testing',message);
//second.js
var mini = require('./mini.js');
var EventEmitter = require('events').EventEmitter;
var ee = new EventEmitter;
mini.on('testing',function(message){
console.log("Second file received a message:",message);
console.log("Passing further");
ee.emit('testing',message);
});
//main.js
var sec = require('./second.js');
sec.on('testing',function(message){
console.log("Main file received the message",message);
});
However, I get
mini.on('testing',function(message){
^
TypeError: undefined is not a function
error when executing the file with node.
What am I doing wrong here?
Thanks
You're not exporting your EventEmitter instance in mini.js. Add this to mini.js:
module.exports = ee;
You'll also need to add a similar line in second.js if you want to export its EventEmitter instance in order to make it available to main.js.
Another problem you'll run into is that you're emitting testing in mini.js before second.js adds its testing event handler, so it will end up missing that event.
This one should work :
This is the content to put inside first.js :
//first.js
var util = require('util'),
EventEmitter = require('events');
function First () {
EventEmitter.call(this)
}
util.inherits(First, EventEmitter);
First.prototype.sendMessage = function (msg) {
this.emit('message', {msg:msg});
};
module.exports = First;
This is the content to put inside second.js :
//second.js
var First = require('./first.js');
var firstEvents = new First();
// listen for the 'message event from first.js'
firstEvents.on('message',function(data){
console.log('recieved data from first.js is : ',data);
});
// to emit message from inside first.js
firstEvents.sendMessage('first message from first.js');
Now run node second.js and you should have the 'message' event fired for you.
You can use this pattern to achieve any level of messaging between modules.
Hope this helps.

Mongoose possible issue

I have an issue using mongoose.
The application I am writing consists in a file watcher that notifies clients about certain events via email and socketio messages.
I made an example that shows the problem:
basically, there is a class called mainFileWatcher that contains a submodule which in turn watches for new files or folders created in the script directory, emitting an "event" event when that happens. The mainFileWatcher listens for that event and calls a static method of a mongoose Client model.
If you run the script setting REPL=true you'll be able to access a watcher.submodule object and manually emit an "event" event.
Now, if you manually trigger the event, you'll see a statement that
says that the "event" event was triggered and an email address as a response.
Otherwhise, if you create a file or a folder in the script folder, you'll
just see that statement. Actually, if you run the script with REPL=true
you'll get the email only after pressing any key, nothing otherwise.
The fact that you don't get the email address as a response means to me that
the code in the promise in mongoose model doesn't get called for some reason.
Here is the code, sorry I couldn't make it shorter
// run
// npm install mongoose bluebird inotify underscore
//
// If you run the script with REPL=true you get an interactive version
// that has as context the filewatcher that emit events in my original code.
// It can be acessed through the watcher.submodule object.
// The watcher triggers a "event" event when you create a file or a folder in the script
// directory.
//
// If you emit manually an "event" event with the watcher.submodule in the repl, you should see a
// statement that "event" was triggered and
// an email address (that belongs to a fake client created by the bootstrap
// function at startup).
// If instead you create a file or a folder in the script folder (or whatever folder you have setted),
// you should see this time you'll have no email response. Actually, if you run with REPL=true,
// you'll have no email response untill you press any key. If you run without REPL, you'll
// have no email response.
'use strict';
var mongoose = require('mongoose');
//mongoose.set('debug', true);
mongoose.Promise = require('bluebird');
var Schema = mongoose.Schema;
var EventEmitter = require('events');
var util = require('util');
var _ = require("underscore");
var Inotify = require('inotify').Inotify;
var inotify = new Inotify();
// Schema declaration
var clientSchema = new Schema({
emails: {
type: [String]
}
}, {strict:false});
clientSchema.statics.findMailSubscriptions = function (subscription, cb) {
this.find({
subscriptions: {$in: [subscription]},
mailNotifications: true
}).exec().then(function (clients) {
if(!clients || clients.length === 0) return cb(null, null);
var emails = [];
clients.forEach(function (client) {
Array.prototype.push.apply(emails, client.emails)
});
return cb(null, emails);
}).catch(function(err){
console.error(err);
})
};
var clientModel = mongoose.model('Client', clientSchema);
// Mongoose connection
mongoose.connect('mongodb://localhost:27017/test', function (err, db) {
if (err) console.error('Mongoose connect error: ', err);
});
mongoose.connection.on('connected', function () {
console.log('Mongoose connected');
});
// bootstrap function: it inserts a fake client in the database
function bootstrap() {
clientModel.findOne({c_id: "testClient"}).then(function (c) {
if(!c) {
var new_c = new clientModel({
"name": "Notifier",
"c_id": "testClient",
"subscriptions": ["orders"],
"registeredTo": "Daniele",
"emails": ["email#example.com"],
"mailNotifications": true
});
new_c.save(function(err){
if (err) console.error('Bootstrap Client Error while saving: ', err.message );
});
}
});
}
// submodule of the main file watcher: it looks for new files created in the script dir
var submoduleOfFileWatcher = function() {
var _this = this;
var handler = function (event) {
var mask = event.mask;
var type = mask & Inotify.IN_ISDIR ? 'directory' : 'file';
if (mask & Inotify.IN_CREATE) {
_this.emit("event", event);
}
}
var watcher = {
path: '.', // here you can change the path to watch if you want
watch_for: Inotify.IN_CREATE,
callback: handler
}
EventEmitter.call(this);
this.in_id = inotify.addWatch(watcher);
}
util.inherits(submoduleOfFileWatcher, EventEmitter);
// Main File Watcher (it contains all the submodules and listensto the events emitted by them)
var mainFileWatcher = function () {
this.start = function() {
bootstrap();
_.bindAll(this, "onEvent");
this.submodule = new submoduleOfFileWatcher();
this.submodule.on("event", this.onEvent)
};
this.onEvent = function() {
console.log("event triggered");
clientModel.findMailSubscriptions("orders", function(err, mails) {
if (err) console.error(err);
console.log(mails); // THIS IS THE CODE THAT OUTPUTS ONLY IF YOU TRIGGER THE "event" EVENT manually
})
}
}
// Instantiate and start the watcher
var watcher = new mainFileWatcher()
watcher.start();
// start the repl if asked
if (process.env.REPL === "true") {
var repl = require('repl');
var replServer = repl.start({
prompt: 'filewatcher via stdin> ',
input: process.stdin,
output: process.stdout
});
replServer.context.watcher = watcher;
}
Just copy and paste the code, install deps and run it.
Things I tried:
I changed the mongoose Promise object to use bluebird promises, hoping that
I could intercept some exception.
I browsed Mongoose calls with node-inspector and indeed the find method gets called and it seems that it throws no exceptions. I really can't figure out what's happening because I don't get any errors at all.
It is not the database connection (I tried to open one just before the findMailSubscriptions call and got an exception for trying to open an already opened connection).
I figure it might be some issues with scopes or promises.
Is there something I am missing about mongoose, or is it just my code that causes this behaviour?

Categories

Resources