ReadLine used to create an interface to read data from the stream
VMS provide the ability to execute scripts in an app
Vm+readline implementation of the simple JS execution command line tool
Development environment: Node4.2.4, with ES6 Arrow function/let/const
Debug Cmder
' Use strict 'Const ReadLine= Require (' ReadLine '); Const VM= Require (' VM ');//Creating InterfacesLet RL =Readline.createinterface ({input:process.stdin, output:process.stdout}); Rl.setprompt ("V+>"); Rl.prompt (); Rl.on (' Line ', (data) ={Let script=Data.trim (); if(script = = = ' exit ')) {rl.close (); return ; } //if you want to execute scripts in the new run context using Runinnewcontext //using runinthiscontext means that the script can access the current context global variables directly //This internal execution script is extremely unsafe.vm.runinthiscontext (script); Rl.prompt ();}); Rl.on (' Close ', () ={Console.log (' Bye, Bye! '); Process.exit (0);});
There are several ways that a VM needs to be concerned:
Runinthiscontext is executed in the current context and can access the current global but cannot access local variables
Runinnewcontext executes in a new container environment and cannot access any data in the current context
Demonstrating the application of Runinnewcontext
' Use strict 'Const ReadLine= Require (' ReadLine '); Const VM= Require (' VM ');//Create a container or sandbox that can provide variables or methods//used in the scope of the scriptConst Contaner ={};contaner.log=Console.log;//Creating InterfacesLet RL =Readline.createinterface ({input:process.stdin, output:process.stdout}); Rl.setprompt ("V+>"); Rl.prompt (); Rl.on (' Line ', (data) ={Let script=Data.trim (); if(script = = = ' exit ')) {rl.close (); return ; } //if you want to execute scripts in the new run context using Runinnewcontext //using runinthiscontext means that the script can access the current context global variables directly //This internal execution script is extremely unsafe. //vm.runinthiscontext (script);Vm.runinnewcontext (script, Contaner);//For example Script:log (' visonme ') = output Visonmerl.prompt ();}); Rl.on (' Close ', () ={Console.log (' Bye, Bye! '); Process.exit (0);});
This can be modified if you want to provide a variable for script access Contaner
Const CONTAINER = { / / script can directly access Accessname variable console:{ // provide output similar to Console.log in the script error:console.error }}; // If you want to provide a custom method for scripting access you can do this = () = { Console.log ("This is myFunction"= { fn:myfunction // provide fn for scripting access MyFunction}
Application of ReadLine and VM modules