Hey I was wondering if there's a js equivalent to cin from c++. I tried using readLine() and prompt as suggested on the internet but I have been thrown Undefined Reference for both functions. Later I found out that readLine and prompt both run on Node.js or smth but I was wondering if there's a command I can use to run smth that's just pure HelloWorld.js and stuff.
(I haven't learned Node.js so correct me if I'm misunderstanding this)
Thanks.
Here's some of my code if it helps at all:
theInput = readline();
I have tried:
const readLine = require('readline');
const theInput = readline.createInterface({
input: process.stdin,
output: process.stdout
});
and
const theInput = prompt("What's your name?");
I'm using codeceptjs with shelljs.
In one of tests I'm invoking go application like this :
const shell = require('shelljs')
shell.exec('./myGoApplication')
When application is started and correctly working I have a CLI that is listening for input from console via keyboard so I can type text and my application is getting it.
But when I execute this command seems its not transferring to the input and application is not invoking commands.
shell.exec('my text')
Does someone know how to make shellJs make command to my CLI waiting for console input?
go cli:
func StartCLI(relay RelayConn) {
go func() {
fmt.Println("[?] To see avaliable commands write /?")
reader := bufio.NewReader(os.Stdin)
for {
text, _ := reader.ReadString('\n')
text = strings.Trim(text, "\n")
switch true {
case strings.HasPrefix(text, "/?"):
fmt.Println(helpText)
default:
relay.Chat("Default Member Simulation chat message")
}
}
}()
}
https://github.com/shelljs/shelljs
As of writing this answer, it is not possible for processes launched via exec to accept input. See issue #424 for details.
From the ShellJS FAQ:
We don't currently support running commands in exec which require interactive input. The correct workaround is to use the native child_process module:
child_process.execFileSync(commandName, [arg1, arg2, ...], {stdio: 'inherit'});
Using npm init as an example:
child_process.execFileSync('npm', ['init'], {stdio: 'inherit'});
Your code should therefore be something like this:
const child_process = require('child_process')
child_process.execFileSync('./myGoApplication', {stdio: 'inherit'})
Setting the stdio option to 'inherit' means that stdin, stdout, and stderr of the child process is sent to the parent processes' (process.stdin, process.stdout, and process.stderr), so you should be able to type in input to your Node.js program to send it to your Go program.
See the documentation on child_process.execFileSync for more deatils.
How to launch cmd by .js file and automatically type some commands in it?
const { exec } = require("child_process");
const open = require("open");
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
readline.question("Launch cmd?", async (name) => {
if (name === "Y") {
await open("cmd.exe", { wait: true }); //how i can write something in cmd?
} else {
process.exit(console.log("You have closed the programm"));
}
});
You can either do something similar as said in this thread.
How to open a command line window in Node.js?
start cmd.exe /K node my-new-script.js parm1 parm2
But if you want to run multiple commands, use a batch script and run that batch script from Nodejs. Batch Scripts are stored in simple text files containing lines with commands that get executed in sequence, one after the other.
require('child_process').exec('cmd /c batfile.bat', function(){
// โฆyou callback code may run hereโฆ
});
You can learn more about the batch script here. https://www.tutorialspoint.com/batch_script/batch_script_overview.htm
I am testing my module with REPL like this:
repl.start({
input: process.stdin,
output: process.stdout
})
.context.MyModule = MyModule;
Is there a way to reload the module automatically, when I change and save it, without having to exit and run repl again?
You can use the chokidar module and force reload (you will lose runtime context in the module, but it should auto-reload).
var ctx = repl.start({
input: process.stdin,
output: process.stdout
})
.context;
ctx.MyModule = require('./mymodule');
chokidar.watch('.', {ignored: /[\/\\]\./}).on('all', function(event, path) {
delete require.cache['./mymodule'];
ctx.MyModule = require('./mymodule');
});
If that doesn't work, I'm happy to play with it a little and get a working solution.
edit: if it doesn't garbage-collect cleanly (there are any open handles/listeners), this will leak each time it reloads. You may need to add a 'clean-exit' function to MyModule to stop everything gracefully, and then call that inside the watch handler.
I'm writing a web app in Node. If I've got some JS file db.js with a function init in it how could I call that function from the command line?
No comment on why you want to do this, or what might be a more standard practice: here is a solution to your question.... Keep in mind that the type of quotes required by your command line may vary.
In your db.js, export the init function. There are many ways, but for example:
module.exports.init = function () {
console.log('hi');
};
Then call it like this, assuming your db.js is in the same directory as your command prompt:
node -e 'require("./db").init()'
If your db.js were a module db.mjs, use a dynamic import to load the module:
node -e 'import("./db.mjs").then( loadedModule => loadedModule.init() )'
To other readers, the OP's init function could have been called anything, it is not important, it is just the specific name used in the question.
Update 2020 - CLI
As #mix3d pointed out you can just run a command where file.js is your file and someFunction is your function optionally followed by parameters separated with spaces
npx run-func file.js someFunction "just some parameter"
That's it.
file.js called in the example above
const someFunction = (param) => console.log('Welcome, your param is', param)
// exporting is crucial
module.exports = { someFunction }
More detailed description
Run directly from CLI (global)
Install
npm i -g run-func
Usage i.e. run function "init", it must be exported, see the bottom
run-func db.js init
or
Run from package.json script (local)
Install
npm i -S run-func
Setup
"scripts": {
"init": "run-func db.js init"
}
Usage
npm run init
Params
Any following arguments will be passed as function parameters init(param1, param2)
run-func db.js init param1 param2
Important
the function (in this example init) must be exported in the file containing it
module.exports = { init };
or ES6 export
export { init };
As per the other answers, add the following to someFile.js
module.exports.someFunction = function () {
console.log('hi');
};
You can then add the following to package.json
"scripts": {
"myScript": "node -e 'require(\"./someFile\").someFunction()'"
}
From the terminal, you can then call
npm run myScript
I find this a much easier way to remember the commands and use them
Try make-runnable.
In db.js, add require('make-runnable'); to the end.
Now you can do:
node db.js init
Any further args would get passed to the init method, in the form of a list or key-value pairs.
Sometimes you want to run a function via CLI, sometimes you want to require it from another module. Here's how to do both.
// file to run
const runMe = () => {}
if (require.main === module) {
runMe()
}
module.exports = runMe
This one is dirty but works :)
I will be calling main() function from my script. Previously I just put calls to main at the end of script. However I did add some other functions and exported them from script (to use functions in some other parts of code) - but I dont want to execute main() function every time I import other functions in other scripts.
So I did this,
in my script i removed call to main(), and instead at the end of script I put this check:
if (process.argv.includes('main')) {
main();
}
So when I want to call that function in CLI: node src/myScript.js main
simple way:
let's say you have db.js file in a helpers directory in project structure.
now go inside helpers directory and go to node console
helpers $ node
2) require db.js file
> var db = require("./db")
3) call your function (in your case its init())
> db.init()
hope this helps
Updated for 2022 - If you've switched to ES Modules, you can't use the require tricks, you'd need to use dynamic imports:
node -e 'import("./db.js").then(dbMod => dbMod.init());'
or with the --experimental-specifier-resolution=node flag:
node --experimental-specifier-resolution=node -e 'import("./db").then(dbMod => dbMod.init());'
If you turn db.js into a module you can require it from db_init.js and just: node db_init.js.
db.js:
module.exports = {
method1: function () { ... },
method2: function () { ... }
}
db_init.js:
var db = require('./db');
db.method1();
db.method2();
I do a IIFE, something like that:
(() => init())();
this code will be executed immediately and invoke the init function.
You can also run TypeScript with ts-node similar to #LeeGoddard answer.
In my case, I wanted to use app and init separately for testing purposes.
// app.ts
export const app = express();
export async function init(): Promise<void> {
// app init logic...
}
npx ts-node -e 'require("./src/app").init();'
npx ts-node -e 'import("./src/app").then(a => a.init());' // esmodule
maybe this method is not what you mean, but who knows it can help
index.js
const arg = process.argv.splice(2);
function printToCli(text){
console.log(text)
}
switch(arg[0]){
case "--run":
printToCli("how are you")
break;
default: console.log("use --run flag");
}
and run command node . --run
command line
probuss-MacBook-Air:fb_v8 probus$ node . --run
how are you
probuss-MacBook-Air:fb_v8 probus$
and you can add more arg[0] , arg[1], arg[2] ... and more
for node . --run -myarg1 -myarg2
If you want to include environment variables from your .env files, you can use env-cmd:
npx env-cmd node -e 'require("./db").init()'
If you want run a specific function in the file too, use run-func:
npx env-cmd npx run-func db.js init someArg
Or, to provide an argument for the accepted answer you'd have to do something like:
npx env-cmd node -e 'require("./db").init(someArg)'
Writing/updating an expression here is less explicit (so easier to miss when you're checking back, for example) than providing different arguments to the commands, so I recommend using env-cmd with run-func.
Note: I also usually add --experimental-modules on the end when necessary.
Inspired by https://github.com/DVLP/run-func/blob/master/index.js
I create https://github.com/JiangWeixian/esrua
if file index.ts
export const welcome = (msg: string) => {
console.log(`hello ${msg}`)
}
just run
esrua ./index.ts welcome -p world
will output hello world
If your file just contains your function, for example:
myFile.js:
function myMethod(someVariable) {
console.log(someVariable)
}
Calling it from the command line like this nothing will happen:
node myFile.js
But if you change your file:
myFile.js:
myMethod("Hello World");
function myMethod(someVariable) {
console.log(someVariable)
}
Now this will work from the command line:
node myFile.js