Bluemix Node js app push Start unsuccessful - node.js

I am using watson conversation service on node js application.
while trying to push application to bluemix. (through command prompt)
After uploading all the files..
0 of 1 instance running, 1 starting
0 of 1 instance running, 1 starting
0 of 1 instance running, 1 starting
0 of 1 instance running, 1 starting
0 of 1 instance running, 1 crashed
FAILED
Start unsuccessful
Kindly help what's the issue..
command prompt
'My coding
var watson=require('watson-developer-cloud');
var conversation =watson.conversation({
url: 'https://gateway.watsonplatform.net/conversation/api',
username:' ',
password:' ',
version:'v1',
version_date:'2017-06-20'
});
var context={};
context.hour=-1;
function prompt(question,callback){
var stdin=process.stdin,
stdout=process.stdout;
stdin.resume();
stdout.write(question);
stdin.once('data',function(data){
callback(data.toString().trim());
});
}
function tConvert(time){
time=time.toString().match(/^([01]\d2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/)||[time];
if(time.length>1){
time=time.slice(1);
time[5]=+time[0]<12?'AM':'PM';
time[0]=+time[0]%12||12;
}
return time.join('');
}
function convMessage(message){
var d=new Date();
var n=tConvert(d.getHours() + ':' + d.getMinutes() + ':00');
context.hour=(n.split(':'))[0];
context.minute=(n.split(':'))[1];
conversation.message({
workspace_id:'09ee7558-0d3e-4af3-8429-14e60be348d7',
input:{'text':message},
context:context
},function(err,response){
if(err){
console.log('error:',err);
}else {
console.log('Watson: ' + response.output.text[0])
prompt('You: ', function(input){
convMessage(input);
});
context=response.context;
}
});
}
convMessage('Hi.');

Your program might run locally. However, to run as Bluemix Node.js app on Cloud Foundry it needs to meet certain requirement. A web app is expected and the health manager checks on the expected port whether your app is alive. If the app cannot be detected it is considered "dead" and the logs will show it as "crashed".
Take a look at the sample app "Conversation Simple" and the main file "server.js" for how the port info is handled.
As an alternative for your code, you could consider setting a health check type of process. It would indicate Bluemix / Cloud Foundry that you don't deploy a regular (Web) app, but something running in the background or executed once.

Related

Using node.js, I cannot get the stdout from a macos app until the process finishes

I've created a helper app with Xcode. It's a command line app that keeps running using RunLoop (because it will do Bluetooth things in the background).
I want to spawn this app using node.js and read its output. I've sucessufully done this with other applications using the spawn method. However, with this MacOS app nothing is visible until the app finishes.
My node.js code:
const { spawn } = require('node:child_process')
const child = spawn(PROCESS)
child.stdout.on('data', data => {
console.log(data.toString());
})
My Swift code (helper app):
import Foundation
var shouldKeepRunning = true
print("app started")
let controller = Controller()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(10)) {
shouldKeepRunning = false
}
while shouldKeepRunning == true && RunLoop.current.run(mode: RunLoop.Mode.default, before: Date.distantFuture) {
}
In node.js app started is only printed after 10 seconds, when the app finishes. When running the app using Terminal, I see app started immediately.
Does anyone know why this happens and how it can be solved?
Thanks!
This question is actually the same: swift "print" doesn't appear in STDOut but 3rd party c library logs do when running in docker on ECS but instead of node.js Docker is not logging the output.
I fixed it by adding the following to the top of my code:
setbuf(stdout, nil)
This will make print() write to stdout directly without waiting for some buffer to be full first.

Node.JS windows service cannot start

I'm using windows-service package to run my script as a windows service.
if (process.argv[2] == "--add") {
logger.info('Starting to add service', global.appRoot + "\\app.js")
ws.add (config.service_name, {programPath: global.appRoot + "\\app.js"});
logger.info('Service added', config.service_name, global.appRoot + "\\app.js")
} else if (process.argv[2] == "--remove") {
logger.info('Removing service', config.service_name)
ws.remove (config.service_name);
logger.info('Service removed', config.service_name)
} else if (process.argv[2] == "--run") {
logger.info('Starting service', config.service_name);
ws.run (logger, function() {
logger.info('Stopping service', config.service_name);
ws.stop()
logger.info('Service stopped')
});
} else if (process.argv[2] == "--stop") {
logger.info('Stopping service', config.service_name);
ws.stop()
logger.info('Service stopped')
}
After running "node service.js --add", I have verified that my windows service is installed correctly with command like below
"C:\Program Files\nodejs\node.exe" "E:\Utils\app.js"
I pasted the command into node.js command prompt and it launched the script correctly.
However, when I tried to start the windows service from the service console, it always complains
Error 1053: The service did not respond to the start or control request in a timely fashiion.
I tried "node service.js --run", it simply prints out the "Starting service" message and hangs there. The underlying script isn't kicked off either.
Verified service log, no error. No script-specific log is generated.
All my script objects are using global.appPath for absolute path reference.
I run out of ideas. Any advice on this matter?

node.js & rabbitmq - publish a message using cli

So I'm trying to do the following from the command line:
> somecommand "Hello world"
will cause my listening node.js application (RabbitMQ) to receive "hello world" and print it to stdout...
Here's my node.js application (app.js) that's listening for "newTrend" events:
var context = require('rabbit.js').createContext();
var sub=null;
context.on('ready', function() {
sub = context.socket('SUB');
sub.setEncoding('utf8');
console.log("Connected to rabbitmq");
sub.on('newTrend',function(data){
console.log(data);
});
});
Start using:
nodejs app.js
But how to send it "newTrend" events via RabbitMQ using just the command line? I have rabbitmqadmin installed.
Is there something stopping you from writing a Node.JS program to act as the client?
#!/usr/bin/env node
var context = require('rabbit.js').createContext();
...
Either that or see if rmqcat will do what you need: https://github.com/squaremo/rmqcat

Dynamic arguments for ZINTERSTORE with node_redis

I'm trying to use the ZINTERSTORE command of redis from node.js using node_redis:
//node.js server code
var redis = require("redis");
var client = redis.createClient();
// ... omitted code ...
exports.searchImages = function(tags, page, callback){
//tags = ["red", "round"]
client.ZINTERSTORE("tmp", tags.length, tags.join(' '), function(err, replies){
//do something
});
}
But the call client.ZINTERSTORE throws the error: [Error: ERR syntax error]. Passing in tags as an array (instead of using tags.join(' ')) throws the same error.
Where can I find the correct syntax for this command? The source code for node_redis has it buried in the javascript parser, but it's tricky to see what's going on without 'stepping through' the code. Is there a good way to do step through debugging with node.js?
There are multiple ways to debug a Redis client with node.js.
First you can rely on the Redis monitor feature to log every commands received by the Redis server:
> src/redis-cli monitor
OK
1371134499.182304 [0 172.16.222.72:51510] "info"
1371134499.185190 [0 172.16.222.72:51510] "zinterstore" "tmp" "2" "red,round"
You can see the zinterstore command received by Redis is ill-formed.
Then, you can activate the debugging mode of node_redis by adding the following line in your script:
redis.debug_mode = true;
It will output the Redis protocol at runtime:
Sending offline command: zinterstore
send ncegcolnx243:6379 id 1: *4
$11
zinterstore
$3
tmp
$1
2
$9
red,round
send_command buffered_writes: 0 should_buffer: false
net read ncegcolnx243:6379 id 1: -ERR syntax error
Then, you can use node.js debugger. Put a debugger breakpoint in the code in the following way:
function search(tags, page, callback) {
debugger; // breakpoint is here
client.ZINTERSTORE("tmp", tags.length, tags, function(err, replies){
console.log(err);
console.log(replies);
callback('ok')
});
}
You can then launch the script with node in debug mode:
$ node debug test.js
< debugger listening on port 5858
connecting... ok
break in D:\Data\NodeTest\test.js:1
1 var redis = require("redis");
2 var client = redis.createClient( 6379, "ncegcolnx243" );
3
debug> help
Commands: run (r), cont (c), next (n), step (s), out (o), backtrace (bt), setBreakpoint (sb), clearBreakpoint (cb),
watch, unwatch, watchers, repl, restart, kill, list, scripts, breakOnException, breakpoints, version
debug> cont
break in D:\Data\NodeTest\test.js:8
6 function search(tags, page, callback) {
7
8 debugger;
9 client.ZINTERSTORE("tmp", tags.length, tags, function(err, replies){
10 console.log(err);
... use n(ext) and s(tep) commands ...
By stepping through the code, you will realize that the command array is not correct because the tags are serialized and processed as a unique parameter.
Changing the code as follows will fix the problem:
var cmd = [ "tmp", tags.length ];
client.zinterstore( cmd.concat(tags), function(err, replies) {
...
});

Node.js SQL Server driver issue - How to troubleshoot

What is the correct way to troubleshoot this error with Node.js on Windows with the SQL Server driver.
events.js:2549: Uncaught Error: 42000: [Microsoft][SQL Server Native Client 11.0
]Syntax error, permission violation, or other nonspecific error
It is not the SQL statement - it works in other tools - like .NET
Doesn't seem to be the SQL connection info - it works in other tools - like .NET
Any thoughts? What is the correct way for completely uninstalling node.js and starting over. I don't think my last install removed all my global modules.
var sql = require('node-sqlserver');
var _ = require('underscore')._;
var connstr = "Driver={SQL Server Native Client 11.0};Server=localhost;" +
"Initial Catalog=CDDB;Trusted_Connection={Yes}";
sql.open(connstr, function (err, conn) {
if (err) {
console.log("Error opening the connection");
return;
} else {
var stmt = "select top 10 * from Client";
conn.query(connstr, stmt, function (err, results) {
if (err) {
console.log("Error running query!");
return;
}
_.each(results, function (row) {
console.log(row[0]);
});
});
}
});
First idea : Are users which runs your node.exe process and the one defined on your application pool - or maybe your current user account if you are using VS.NET to check your code are the same ?
To troubleshoot :
I would use node-inspector - it allows to set up breakpoints onto your node.js code
To install it :
npm install -g node-inspector
To run it :
node --debug your-nodeapp-file.js
Launch another command line and run the following program :
node-inspector
Sorry but i do not have SQL Server to try your code, hope this help anyway.

Resources