Node.js javascript command line while server running? - javascript

If I have a node.js web server running with express, is there a way to get a command line? Kind of like the way the browser has a javascript console. I want to type in variables and inspect them in node.js runtime.
If I type in 'node' then it gives me a command line. but if I type in 'node server.js' that command line is not available. How can I make the command line always available (in bottom of screen) regardless of the server's state?

To do this type node --inspect server.js
Then to connect to it type in chrome://inspect/ in url bar of Chrome. Then click "inspect" on that instance under Remote Target. Then I found I can see variables/objects that are under the global namespace.
Also, a very basic way to add keyboard interaction on the server window itself without having to connect to it:
var readline = require('readline');
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
setInterval(function() {
console.log('server stuff');
}, 1000);
process.stdin.on('keypress', (str, key) => {
if(key.sequence === '\u0003') {
console.log('ctrl-c pressed');
process.exit();
}
console.log('you pressed: ' + key.name);
});

Related

How do I use Node JS to execute a minecraft command on a wrapped minecraft server?

I am making a node discord bot that would have the ability to control a minecraft server, but for some reason I cannot get the bot to execute minecraft commands on the server itself.
Right now the bot receives normal discord strings from messages and interprets them as commands. This is the code I use to start the server:
var svEnv = cp.spawn("java", [
"-Xms4096M",
"-Xmx4096M",
"-jar",
"server.jar",
"nogui"
], { shell: true, detached: true, cwd: `${config.server.directoryPath}`, stdio: [
"inherit",
"inherit",
"inherit",
"ipc"
]});
svEnv.stdout.on("data", out => {
console.log(`Server Feedback: ${out}`);
})
svEnv.stderr.on("data", err => {
if (!(err == "^C")){
console.error(`~Server Error: ${err}`);
}
})
This is the code I'm using to try to execute the commands:
svEnv.stdin.write(`${cmd}\n`);
Whenever I attempt to use the code above to execute a command, the server doesn't respond at all. It's as if it doesn't even receive the input.
All the solutions I have visited, even those with the same exact use case as myself have said this is the correct way to implement this. I have to guess that the reason it doesn't work is because of the way I have the child process spawn configured.
Basically what I'm asking is how does the spawned process need to be configured to receive commands?
Please Note: This is my first time using the child process module in node js, so if you have any tips on how it works please let me know.
The problem is that you set standard input to inherit. If you want to be able to write to it like that, then set it to pipe instead.

JavaScript file can't work while the code work with node in Terminal

I start a java client listening on localhost:8887
And I try this
var net = require('net')
var coon = net.connect(8887,'127.0.0.1')
coon.write('hi')
coon.destroy()
in Terminal with node. The client get the message.
Then I write it into a file test.js and use 'node test.js' in the Terminal, but the client can't get the message. How can I solve this problem.
I add
console.log(coon.remoteAddress+':'+coon.remotePort)
in the code. When I run 'node test.js', it shows that 'undefined:undefined'
Chances are you type into the terminal slow enough for the connection to be made. When you run the whole script, you're attempting to write before there is a connection.
Use the 3rd connectionListener argument
const coon = net.connect(8887, 'localhost', () => {
coon.write('hi');
coon.destroy();
});
See https://nodejs.org/api/net.html#net_net_connect_port_host_connectlistener

HTTP Server stops after some time (Node.js)

INFO: I'm referring to this question I asked on Super User, but couldn't get an answer and I think this is a good place to ask, since the problem is probably code related.
I'm currently running a simple Node.JS server with express.js on my RaspberryPi with Debian installed on it. Everything works fine, but every morning I wake up to see my server isn't running anymore (the server process I started with the command node main.js).
My first guess was, that the Pi has some kind of sleep mode, which it enters after a couple of hours without traffic/etc, and which shuts down the server, but I also run a dydns-client, which is still up every morning (I also was informed, that the RaspberryPi doesn't come with a sleep mode).
I wrote a simple script to check whether the process is running and writes it into a log file, but today morning I had to notice, that this script was wasn't running as well (only for around two hours, it logs the server state every 15 seconds and the last state was running).
Here is the script:
#!/bin/sh
MATCH="SOME_PROCESS_NAME"
while [ true ]
do
if [ "$(ps -ef | grep ${MATCH} | grep -v grep)" ]; then
echo "$(date): Process is running ..."
else
echo "$(date): Process has ended ..."
fi
sleep 15
done
Is there a way to track a process after I started it to check tomorrow morning, what killed my process or why it ended (the script obviously didn't work)?
The server itself looks pretty simple and I don't think there is some kind of auto-shutdown I missed. Here is the code I used.
var express = require('express');
var path = require('path');
var server = express();
server.use(express.static(path.join(__dirname, 'public')));
server.listen(1337);
console.log("Server listening (PORT: " + 1337 + ") ...");
Any idea what to do, to keep the server running/find out what is the stopping reason?
UPDATE: I received a working answer over at RaspberryPi-stackexchange.
My guess is the Raspberry Pi restarts at midnight or something similar. to fix this maybe add an entry for your server process rc.local file. you can add commands to the rc.local file by editing /etc/rc.local
Would this helps https://raspberrypi.stackexchange.com/questions/8741/when-does-the-os-kill-an-application ?
I would like to suggest a different approach to monitor your process until you can get more information, to edit, then check, then start (wrote on the fly)
var fs = require('fs')
var spawn = require('child_process');
var child = spawn(process.argv[0], 'your/bin.js', {stdio:['ignore', 'pipe', 'pipe']})
child.stdout.pipe(fs.createReadStream('stdout.log'))
child.stderr.pipe(fs.createReadStream('stderr.log'))
child.on('error', function (err) {
fs.writeFile('error.log', JSON.stringify(err), function () { /* void */ })
})
child.on('close', function (code, signal) {
fs.writeFile('exit.log', "code="+code+" signal="+signal, function () { /* void */ })
})

How can I setup a testing environment for testing with selenium and phantomjs?

I am trying to setup environment for headless testing using Selenium and PhantomJS.
Setting UP phantomjs:
I have made a folder c:/phantomjs and put all the phantomjs script files there (after downloading).
Then I created a folder C:\xampp\htdocs\testPhantomJS
Now I installed nodeJS in my system.
Then I traversed to the C:\xampp\htdocs\testPhantomJS in the command prompt and installed phantomJS like this:
C:\xampp\htdocs\testPhantomJS>npm install -g phantomjs
The image states a different location. Thats because it was taken from my colleague's computer. We both are working on same installation, and he sent me the image for reference. That's why its different with my folder location, but the location I stated, it is the one I worked on.
Now on typing phantomjs on command prompt, when we are typing
C:\xampp\htdocs\testPhantomJS>phantomjs
phantom>
Setting Up Selenium-Webdriver
I traversed to C:\xampp\htdocs\testPhantomJS in the command prompt and installed selenium webdriver like this:
C:\xampp\htdocs\testPhantomJS>npm install selenium-webdriver
After installation, the folder structure is like this:
Now I have a test-script test.js which is like this:
describe('Test example.com', function(){
before(function(done) {
client.init().url('http://google.com', done);
});
describe('Check homepage', function(){
it('should see the correct title', function(done) {
client.getTitle(function(err, title){
expect(title).to.have.string('Example Domain');
done();
});
});
it('should see the body', function(done) {
client.getText('p', function(err, p){
expect(p).to.have.string(
'for illustrative examples in documents.'
);
done();
})
});
});
after(function(done) {
client.end();
done();
});
});
The problem is, where should I put the above script, and how shall I run it?
I just don't need to run using the phantomjs only, I need to test with both phantomjs and selenium.
This solution is coming from this pretty neat tutorial on how to setup testing with selenium and phantomjs: http://code.tutsplus.com/tutorials/headless-functional-testing-with-selenium-and-phantomjs--net-30545
Here is some of the tutorial below:
Combining Everything
Now that we have all the pieces, we have to put everything together.
Remember: before running any tests, you have to run Selenium Server:
1
java -jar selenium-server-standalone-2.28.0.jar
Selenium will run PhantomJS internally; you don't have to worry about that.
Now, we need to connect to Selenium from our JavaScript. Here's a sample snippet, which will initiate a connection to Selenium and have a ready object to control our Selenium instance:
// Use webdriverjs to create a Selenium Client
var client = require('webdriverjs').remote({
desiredCapabilities: {
// You may choose other browsers
// http://code.google.com/p/selenium/wiki/DesiredCapabilities
browserName: 'phantomjs'
},
// webdriverjs has a lot of output which is generally useless
// However, if anything goes wrong, remove this to see more details
logLevel: 'silent'
});
client.init();
Now, we can describe our tests and use the client variable to control the browser.
A full reference for the webdriverjs API is available in the documentation, but here's a short example:
client.url('http://example.com/')
client.getTitle(function(title){
console.log('Title is', title);
});
client.setValue('#field', 'value');
client.submitForm();
client.end();
Let's use the Mocha and Chai syntax to describe a test; we'll test some properties of the example.com web page:
describe('Test example.com', function(){
before(function(done) {
client.init().url('http://example.com', done);
});
describe('Check homepage', function(){
it('should see the correct title', function(done) {
client.getTitle(function(title){
expect(title).to.have.string('Example Domain');
done();
});
});
it('should see the body', function(done) {
client.getText('p', function(p){
expect(title).to.have.string(
'for illustrative examples in documents.'
);
done();
})
});
});
after(function(done) {
client.end();
done();
});
});
You might want to share one client initialization over many test files. Create a small Node module to initialize and import it into every test file:
client.js:
exports.client = require('webdriverjs').remote({
// Settings
};
test.js:
var client = require('./client').client;
var expect = require('chai').expect;
// Perform tests
EDIT based on the question in the comments:
Here is how to install the selenium server, and yes you need to do it.
Selenium
Download Selenium Server. It is distributed as a single jar file, which you run simply:
java -jar selenium-server-standalone-2.28.0.jar
As soon as you execute this command, it boots up a server to which your testing code will connect later on. Please note that you will need to run Selenium Server every time that you run your tests.

Restart a node.js app from code level

I've an app which initially creates static config files (once) and after files were written I need to reinitialize/restart the application.
Is there something to restart a node.js app from itself?
This is required cause I've an application running in two runlevels in node.js.
The initial one starts completly synchronus and after this level has been completed app is in async runlevel in a previously started environment.
I know there are tools like nodemon but that's not what I need in my case.
I tried to kill the app via process.kill() which is working but I can't listen to the kill event:
// Add the listener
process.on('exit', function(code) {
console.log('About to exit with code:', code);
// Start app again but how?
});
// Kill application
process.kill();
Or is there a better, cleaner way to handle this?
Found a working case to get node.js restarted from app itself:
Example:
// Optional part (if there's an running webserver which blocks a port required for next startup
try {
APP.webserver.close(); // Express.js instance
APP.logger("Webserver was halted", 'success');
} catch (e) {
APP.logger("Cant't stop webserver:", 'error'); // No server started
APP.logger(e, 'error');
}
// First I create an exec command which is executed before current process is killed
var cmd = "node " + APP.config.settings.ROOT_DIR + 'app.js';
// Then I look if there's already something ele killing the process
if (APP.killed === undefined) {
APP.killed = true;
// Then I excute the command and kill the app if starting was successful
var exec = require('child_process').exec;
exec(cmd, function () {
APP.logger('APPLICATION RESTARTED', 'success');
process.kill();
});
}
The only con I can see here is to loose outputs on console but if anything is logged into logfiles it's not a problem.

Categories

Resources