Using MySQL on SilkJS Under OSX Lion - javascript

I'd like to use MySQL from SilkJS under OSX Lion, but can't find the exact steps to get it to work. I followed the general instructions found here:
Perform the SilkJS OSX Lion Quick Install
Install MySQL
Load MySQL from SilkJS REPL
Download/configure:
$ curl http://silkjs.org/install-osx.sh | sh
$ sudo port install mysql5-server +mysql5
$ sudo -u _mysql mysql_install_db5
$ sudo port load mysql5-server
Starting the SilkJS REPL, I ran:
$ silkjs
SilkJS> var MySQL = require('MySQL');
undefined
SilkJS> var SQL = new MySQL();
undefined
SilkJS> SQL.connect();
interpreter line 19 (main):
(object) :
SilkJS> SQL.startTransaction();
Caught Signal 11 for process: 77312
How can I run a simple MySQL query from SilkJS under Lion?

Fresh web install of silkjs on OSX Lion:
mschwartz#dionysus:~/src$ curl http://silkjs.org/install-osx.sh | sh
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 1666 100 1666 0 0 3553 0 --:--:-- --:--:-- --:--:-- 79333
Installing SilkJS in /usr/local/silkjs
You may be asked to enter your password.
This is so the /usr/local directory can be made writable for the install.
Password:
Downloading SilkJS
######################################################################## 100.0%
Installation complete.
You need to add /usr/local/bin to your PATH environment variable.
This can be done by adding this line to your .bashrc file:
export PATH=/usr/local/bin:$PATH
You can run SilkJS with the following command:
$ silkjs
You can run the SilkJS HTTP Server with the following command:
$ httpd-silk.js yourapp.js
For instructions on setting up a WWW site for httpd-silk.js, see
http://silkjs.org/http-server/
Now to see it works:
mschwartz#dionysus:~/src$ silkjs
SilkJS> console.dir(require('MySQL'));
undefined line 1 (eval):
function () {
this.queryCount = 0;
this.handle = null;
}
undefined
SilkJS>
Note the console.dir() shows a function. The rest of the methods defined as properties of the function (constructor). So you must construct a MySQL() object:
SilkJS> var mysql = require('MySQL');
SilkJS> m = new mysql();
SilkJS> console.log(m.connect)
function (host, user, passwd, db) {
if (!this.handle) {
host = host || Config.mysql.host;
user = user || Config.mysql.user;
passwd = passwd !== undefined ? passwd : Config.mysql.passwd;
db = db || Config.mysql.db;
this.handle = mysql.connect(host, user, passwd, db);
}
}
undefined
SilkJS>
Now, in order to connect, you have to pass in host, user, passwd, and db. Or if you're running in the httpd environment, you set Config.mysql, something like this:
Config.mysql = {
host: 'localhost', // or some other host running MySQL server
user: 'someuser', // username to authenticate in MySQL server
passwd: 'whatever', // password of username in MySQL server
db: 'database_name" // name of database in MySQL server to connect to
};
Then the HTTP server will create a global SQL object available from request to request. This is automatic, you can just use SQL.getDataRows(), SQL.getScalar(), and so on.

Related

I'm facing problems connecting express to Rabbit MQ

On visiting local host 3000 I get Cannot GET / before using postman.
during the process of sending POST request in postman to the local host my program fails and I get this Error
`node:internal/process/promises:288
triggerUncaughtException(err, true /* fromPromise */);
^
Error: connect ECONNREFUSED ::1:5672
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1487:16) {
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 5672`
config.js
----------
module.exports = {
rabbitMQ: {
url: "amqp://localhost",
exchangeName: "logExchange",
},
};
Producer.js
-----------
const amqp = require("amqplib");
const config = require("./config");
//step 1 : Connect to the rabbitmq server
//step 2 : Create a new channel on that connection
//step 3 : Create the exchange
//step 4 : Publish the message to the exchange with a routing key
class Producer {
channel;
async createChannel() {
const connection = await amqp.connect(config.rabbitMQ.url);
this.channel = await connection.createChannel();
}
async publishMessage(routingKey, message) {
if (!this.channel) {
await this.createChannel();
}
const exchangeName = config.rabbitMQ.exchangeName;
await this.channel.assertExchange(exchangeName, "direct");
const logDetails = {
logType: routingKey,
message: message,
dateTime: new Date(),
};
await this.channel.publish(
exchangeName,
routingKey,
Buffer.from(JSON.stringify(logDetails))
);
console.log(
`The new ${routingKey} log is sent to exchange ${exchangeName}`
);
}
}
module.exports = Producer;
Server.js
----------
`const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const Producer = require("./producer");
const producer = new Producer();
app.use(bodyParser.json("application/json"));
app.post("/sendLog", async (req, res, next) => {
await producer.publishMessage(req.body.logType, req.body.message);
res.send();
});
app.listen(3000, () => {
console.log("Server started...");
});`
I am a Junior Intern ad was following along an youtube video by https://www.youtube.com/watch?v=igaVS0S1hA4 by Computerix to help me understand the concepts
I tried restarting the rabbitMQ and express server and running it on different ports but didnt solve the problem
This is Big Picture
Postman -> Express Server -> RabbitMQ -> node.js
#1 Postman send message to Express with Message Types and payload by POST call
#2 Express Server forward message to Rabbit MQ by publish
#3 RabbitMQ - push the messages into own message queue
#4 Each consumer received own message from RabbitMQ. It was binned before.
There are many complex options(order, priority) but in here talking about basic and simple model.
Steps
We needs following three steps.
#1 : Install
1.1 docker (easy way to container to run RabbitMQ)
1.2 node
1.3 demo source
git clone https://github.com/charbelh3/RabbitMQ-Logger-Example.git
File structure
1.4 install node library
At RabbitMQ-Logger-Example\infoMS directory
npm install amqplib
At RabbitMQ-Logger-Example\loggerMS directory
npm install amqplib express body-parser
At RabbitMQ-Logger-Example\warningAndErrorMS directory
npm install amqplib
1.5 Install Postman
1.6 Install Git Bash - I will using git bash terminal. It similar bash terminal in Linux - If you using Linux, skip this.
#2 : Binding
2.1 running RabbitMQ
Save this code as docker-compose.yml
version: "3.8"
services:
rabbitmq:
image: rabbitmq:management-alpine
container_name: 'rabbitmq'
ports:
- 5672:5672
- 15672:15672
volumes:
- ~/.docker-conf/rabbitmq/data/:/var/lib/rabbitmq/
- ~/.docker-conf/rabbitmq/log/:/var/log/rabbitmq
networks:
- rabbitmq_go_net
networks:
rabbitmq_go_net:
driver: bridge
Run it
docker compose up
If docker compose version 1.x
docker-compose up
Open your browser with this URL
http://localhost:15672/
2.2 Run express and all node.js
At RabbitMQ-Logger-Example\infoMS directory
node app.js
At RabbitMQ-Logger-Example\loggerMS directory
node server.js
At RabbitMQ-Logger-Example\warningAndErrorMS directory
node app.js
Now ready to go
#3 : Message
Run Postman,
#1 Make own collection
#2 Make Three requests
One of Request - Send Info Message
#1 Select POST method
#2 Enter URL
localhost:3000/sendLog
#3 Click Body Tab
#4 Select Raw radio button
#5 Enter message into body
{
"logType" : "Info",
"message" : "I am Info message"
}
#6 Select JSON
#7 Press Send Button
If you see , You are success!
Other two different type message is same content
Just difference is logType's value.
Send Warning Message Request
For Warning
{
"logType" : "Warning",
"message" : "I am Warning message"
}
Send Error Message Request
For Error
{
"logType" : "Error",
"message" : "I am Error message"
}
This is real screen all of things!
If you browser, RabbitMQ content, you found many things.
This is one of it for Info channel information.
If want to terminate RabbitMQ
CTRL+C
docker compose down
Enjoy RabbitMQ!

CubeJS PostgresDriver fails authentication but it works in terminal

I can connect to my database just fine by entering psql -U <db_user> -W -h localhost -p <db_port> -d <db_name>. However, when I set up that same connection in a Cubejs backend, queries like http://localhost:4000/cubejs-api/v1/load?query=... return {"error": "Error: password authentication failed for user \"<db_user>\""}.
The database is actually connected via SSH tunnel. I've connected a truly local db to Cubejs before, so I suspect this might be causing trouble.
I attempt the connection like so
new PostgresDriver({
database: "<db_name>",
host: "localhost",
user: "<db_user>",
password: "<db_password>"
})
3. The logs from the Postgres database only show stuff that looks unrelated to my connection attempts:
2020-11-18 23:42:25 UTC::#:[6677]:LOG: checkpoint starting: time
2020-11-18 23:42:25 UTC::#:[6677]:LOG: checkpoint complete: wrote 1 buffers (0.0%); 0 WAL file(s) added, 0 removed, 1 recycled; write=0.101 s, sync=0.001 s, total=0.115 s; sync files=1, longest=0.001 s, average=0.001 s; distance=65536 kB, estimate=65623 kB

how to get the port number from the service name using nodejs

We are developing a WebSocket server using Nodejs with socket.io
I have used createServer method from class HTTP and then listen to a port as follows :
var server = http.createServer();
server.listen(port, function () {
...
}
Now The problem is that I only have the service name
and listening to a service doesn't work :
var server = http.createServer();
server.listen(service, function () {
...
}
So I need to read and parse the file /etc/services to get the port associated with the service as follows :
var str = fs.readFileSync(filename).toString();
var serviceline = str.match( port+".*tcp" );
var port = serviceline[0].match( "[0-9]+" )
Is there a simpler way to get the port from the service?
Thanks in advance
Jean-Marie
You can use find-process to find port from process or vice-versa
Command line usage
npm install find-process -g
Usage: find-process [options] <keyword>
Options:
-V, --version output the version number
-t, --type <type> find process by keyword type (pid|port|name)
-p, --port find process by port
-h, --help output usage information
Examples:
$ find-process node # find by name "node"
$ find-process 111 # find by pid "111"
$ find-process -p 80 # find by port "80"
$ find-process -t port 80 # find by port "80"
Code usage
npm install find-process --save
const find = require('find-process');
find('pid', 12345)
.then(function (list) {
console.log(list);
}, function (err) {
console.log(err.stack || err);
})
I have used this to find process from the port but I think it provides a reverse way to or you can skim down to its repo and pick the code you needed.
I don't need a server port but the port corresponding to a service name
for instance having the following service "wsgw" specified in file /etc/services
wsgw 8001/tcp # websocket gateway
I need to get the value 8001 before running the server listening to this port this way :
var server = http.createServer();
server.listen(8001, function () {
...
listening to a service as below doesn't work :
var server = http.createServer();
server.listen("wsgw", function () {
...
note : finding a port from a process doesn't help me as it is not a process but a service

mosquitto+mqtt.js got "Connection refused: Not authorized"

I built mosquitto on CentOS7 and a node.js client based on mqtt.js,installing with
yum install mosquitto mosquitto-clients
The local test
> mosquitto_sub -h localhost -t test
> mosquitto_pub -h localhost -t test -m "hello world"
works fine, but when I ran:
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://192.168.1.70')
client.on('connect', function () {
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
I got Error: Connection refused: Not authorized
The mosquitto.conf is like:
pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
allow_anonymous true
and I use systemctl restart mosquitto to restart it several time, which doesn't help. The firewall is down and log file stays empty.
A screenshot on status:
Can anyone help please?
UPDATE:
It turns out that the mosquitto service is somehow broken as the status shows Active: active (exited).
I use mosquitto -p 1884 -v cmd to run another mosquitto process on port 1884, it works fine. Then I try to reload the conf using
> /etc/init.d/mosquitto reload. It gives me
Reloading mosquitto configuration (via systemctl): Job for mosquitto.service invalid.
[FAILED]
So there IS something wrong with mosquitto service.
Not a final solution but I manage to fix this by remove-reboot-install process, the status went green as follow:
SOLUTION
I managed to find out the reason it doesn't work. I've installed rabbitmq on my server, it uses its "rabbitmq_mqtt" which consumes port 1883. Reassigning a port will solve this problem.
I managed to find out the reason. I've installed rabbitmq on my server, it uses its "rabbitmq_mqtt" which consumes port 1883. Reassigning a port will solve this problem. The problem is simple, but yeah, the CLI should have given me more information.
You need to add the authorize information to mqtt connect method.Just like this.
var client=mqtt.connect("ws://192.168.1.1", {
username: "yourUsername",
password: "yourPassword"
}
Add the Authorization details for the client to connect
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://192.168.1.70', {
username: '<username>',
password: '<password>'
});
client.on('connect', function () {
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})

Postgresql on OpenShift 2, using node.js

I have an app that uses Node.js and Postgresql on OpenShift, I can connect locally to the database and make queries, but I can't get it to work on the openshift server. When I push to server, I get this error:
Waiting for application port (8080) become available ...
Application 'myapp' failed to start (port 8080 not available)
But Im using the port 8080...
My openshift ports are:
Service --- Local --------------- OpenShift
node ------ 127.0.0.1:8080 => 127.8.120.129:8080
postgresql 127.0.0.1:5432 => 127.8.120.130:5432
And here I write the important code line.
First, the server.js:
...
var db = require('./postgresql/database.js');
db.sync();
...
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
server.listen(server_port, server_ip_address, function () {});
...
And database.js:
var Sequelize = require('sequelize');
var bd_url = process.env.OPENSHIFT_POSTGRESQL_DB_URL || 'postgres://'user':'pass'#127.0.0.1:5432/sw'
var sequelize = new Sequelize(bd_url, {
dialect: 'postgres',
dialectOptions: {}
});
module.exports = sequelize;
Does anyone know what can fail?
Thanks!
OpenShift provides a default web server (written in Ruby) on almost every container/cartridge you create.
Every service is started using the "start" service hook, located at:
$OPENSHIFT_REPO_DIR/.openshift/action_hooks/start
You may find a line like this one:
[]\> nohup $OPENSHIFT_REPO_DIR/diy/testrubyserver.rb $OPENSHIFT_DIY_IP $OPENSHIFT_REPO_DIR/diy |& /usr/bin/logshifter -tag diy &
In order to verify which application is using port 8080, you can execute "oo-lists-ports" command.
This command is just an alias for "lsof" command.
Execute it without any arguments and you'll obtain the application that it's locking your port 8080 (in my case):
[]\> oo-lists-ports
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 88451 1027 10u IPv4 392176 0t0 TCP 127.2.1.129:8080 (LISTEN)
[]\>
With the above information (PID), you just need to kill the related process:
(in my case)
[]\> ps -ef |grep 88451
1027 62829 61960 0 08:33 pts/0 00:00:00 grep 88451
1027 88451 1 0 Jun21 ? 00:00:16 node faceBot.js
[]\> kill -9 88451
After killing the process that is locking your port 8080 you will be able to run your Node JS stack on that port.
Regards

Categories