Run another Node JS file in command prompt without closing and restarting it - node.js

Being New in NodeJS Whenever I run my node JS file in command prompt. I have to close the console window and type the same procedure again. is there any way that i have to not run again and again command prompt.

Use ctrl+c in command prompt and you can use your same command prompt window to run the same program.

For example there are two node.js files.
nodeOne.js
nodeTwo.js
If, these nodes need a port to run, configure both on different port numbers.
e.g. 8080 for nodeOne.js and 8081 for nodeTwo.js
Now, open two instances of 'cmd' and execute both nodes separately.

I'd use "start node whatever.js".
That'll open it up in a separate window, which you can kill whenever and just hit Up arrow on the original cmd window to run the same command.
On the off chance, you're killing the original cmd just to restart node, ctrl-c a couple times should kill it, shouldn't it?
Then up arrow and you've got the last command again.

This could use a little more context, but I assume you are running something like this on the command line:
node my_file.js
Or just:
./my_file.js
Whenever you write command line scripts like this, it's good to call process.exit to tell Node when you're done. So, for example:
#!/usr/bin/env node
function myFunction () {
// Do some stuff that takes a while...
return Promise.resolve()
}
myFunction()
.then(result => {
console.log(result)
process.exit(0)
})
.catch(error => {
console.error(error)
process.exit(1)
})
And if your script is just hanging and not stopping, you can always hit Ctrl + C to abort.

Related

Worker thread postMessage() vs command line command

I recently learned about Worker threads in Node JS. I was trying to create a worker thread to run Stockfish chess engine in node js.
The npm package I am using for this is called stockfish. I tried using node-stockfish before this but it was not installing with npm as it was using an older version of the type definition for the "AbortSignal" variable apparently causing compatibility issues.
For the current npm package that I am using even though I was able to install it successfully, I could find very little documentation on how to use it. So I tried out a few ideas.
import { Worker } from "worker_threads";
const engine = new Worker("./node_modules/stockfish/src/stockfish.js")
engine.on('message', (data) => console.log(data))
engine.postMessage('position startpos move e2e4 e7e5')
engine.postMessage('go movetime 3000')
Here I tried to run the stockfish.js as a worker thread and send commands to it with the postMessage() function. This however did not work and it gave the following output:
worker.js received unknown command undefined
position startpos move e2e4 e7e5
worker.js received unknown command undefined
go movetime 3000
But I know these commands are valid commands if I run the same js from the command line like so:
It might be because I am using the flags --experimental-wasm-threads and --experimental-wasm-simd when I am running it from the command line. I found this command to run it from the little documentation that was present. But I don't know how to mention these flags when I run it through a worker thread.
Otherwise it could also be that I don't understand how worker threads work yet and postMessage() is not the same as sending it a command from the command line.
Any help is greatly appreciated.
I switched to using stockfish.wasm library instead. With this library I was able to achieve what I wanted and I don't need to use any worker threads for now. Maybe I can add this to a worker thread if required later. Here is a simple example:
const Stockfish = require("stockfish.wasm")
Stockfish().then((engine) => {
engine.addMessageListener((output) => {
console.log(output);
// Do something with the output data here
})
engine.postMessage("uci");
engine.postMessage("ucinewgame");
engine.postMessage("position startpos");
engine.postMessage("go depth 20");
});

Interract with a .exe program with js instead of typing in the program

Hello I'm tryna make a Skyrim server Dashboard.
The server look like this =>
On this server i can type some command like this =>
when I manualy wrote /help and it show the output.
I tried to run the executable in node js, the server is working, I can join it, And I can see the output on my VSCode Terminal
But I can't input some text or command
Hope you can help me thanks in advance.
##Its my first ask
Add shell: true to the spawn method so you can still pass commands to the process.
const child = require('child_process').spawn("C:/SkyrimTogetherServer.exe", {
shell: true
});

Running MacOS shortcuts shell command from node script

I am trying to run MacOS shortcuts via NodeJS script. To achieve that I created shortcuts in the MacOS Shortcuts app, which normally run in the terminal (ZSH) by typing shortcuts run shortcutname (Docs). They work fine when typing them directly into the terminal, but not when called from a NodeJS script.
My script looks like this:
exec('shortcuts run shortcutname', (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
When starting the script from the terminal node script.js it does nothing. It does not return anything nor does it finish. I tried replacing the command shortcuts run shortcutname by other commands the system should know. For example ls, or git. They all work. Also when I leave out the shortcutname in the end, it complains about the missing parameter.
I was suspecting missing access rights, but apparently NodeJS runs as my normal user. Running whoami in script context returns my user name.
NODE_DEBUG=cluster,net,http,fs,tls,module,timers node script.js did not show anything unusual. I also tried using the full path of the binary. which shortcuts gave me /usr/bin/shortcuts. Which I used in my script /usr/bin/shortcuts run shortcutname.
What am I missing? Thanks in advance!
Though I thought I tested it, I found the solution:
execSync instead of exec works
It’d be cool if someone could explain why exec wouldn’t work.
Cheers!

node.js child process change a directory and run the process

I try to run external application in node.js with child process like the following
var cp = require("child_process");
cp.exec("cd "+path+" && ./run.sh",function(error,stdout,stderr){
})
However when I try to run it stuck, without entering the callback
run.sh starts a server, when I execute it with cp.exec I expect it run asynchronously, such that my application doesn't wait until server termination. In callback I want to work with server.
Please help me to solve this.
cp.exec get the working directory in parameter options
http://nodejs.org/docs/latest/api/child_process.html#child_process_child_process_exec_command_options_callback
Use
var cp = require("child_process");
cp.exec("./run.sh", {cwd: path}, function(error,stdout,stderr){
});
for running script in the "path" directory.
The quotes are interpreted by the shell, you cannot see them if you just look at ps output.

Stop Node server in terminal and return to file in vim

I am new to Node and vim.
I have the following code file, server.js open in vim:
var http = require("http");
function onRequest(request, response) {
console.log("Request received");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started");
When I enter vim "command" mode and type:
:!node server.js
Things work as expected (I think). The window changes to the standard terminal window, and if I open a browser and navigate to localhost on port 8888, the silly "Hello World" text is displayed.
The terminal displays the "Server has started" text, and the output that the request was received. All is well.
When I close the browser window, and type Ctrl-z to stop the Node server, the terminal displays [1}+ stopped vim server.js, but does not return me to my code file in vim.
If I return to vim by typing vim, vim opens into the same directory, but my file is not open. If I try to open the file, vim complains about a duplicate swap file. Obviously I can use the [R]ecover option, but it seems like I am missing a step.
What am I missing here?
I have googled, and searched SO, but I am not sure what I am asking for beyond the title of this question (which has not produced the answer I am looking for, or if it did, I didn;t recognize it). I am just new enough that I am unsure if I am missing something about the terminal, or vim, or *nix.
Thanks in advance . . .
UPDATE: It occurs to me I never clearly state what I am after - I am wanting to stop the server in the terminal and return to the open file in vim. As Tadman mentions below, I knew I was probably attempting to open an additional editor instance. What I was unclear on was how to return to the existing instance. Trying Tadman's suggestion now.
You're creating a sub-shell to run node, suspending that with ^Z and then open a new copy of vim when you do your next step. Now you have two editors running, so you get an error about the swap file.
Why not either do this in a separate shell, which is what most people tend to do, or use ^C to stop the server and return to your editor?

Resources