windows command line javascript

2020-06-11 13:34发布

I'm trying to run javascript from a windows command line via script

cscript //NoLogo test.js

However, I can't find any predefined objects which are available. I'm totally at a loss - Can't get hello world to work:

System.print("Hello, World!")

results in "System" is undefined

Is there another way I should be running this - like through .NET runtime?

Thanks

jeff

5条回答
家丑人穷心不美
2楼-- · 2020-06-11 14:07

Try WScript:

WScript.Echo('hello world');
查看更多
The star\"
3楼-- · 2020-06-11 14:09

If you really want to run JavaScript in a shell, then you should consider installing Node.js

http://javascript.cs.lmu.edu/notes/commandlinejs/

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-06-11 14:09

That is actually JScript and when run with cscript or wscript, it's under the Windows Scripting Host environment, which has no real similarity with web-based javascript.

Windows Scripting Host reference

查看更多
霸刀☆藐视天下
5楼-- · 2020-06-11 14:31

You are using the Windows Scripting Host.

You can say things like:

WScript.Echo("Hello, World.");

It's all COM-based, so you instantiate ActiveX controls to do anything useful:

var y = new ActiveXObject("Scripting.Dictionary");
y.add ("a", "test");
if (y.Exists("a"))
   WScript.Echo("true");

Or:

var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
// Get a File object to query.
f1 = fso.GetFile("c:\\detlog.txt");   
// Print information.
Response.Write("File last modified: " + f1.DateLastModified);

See Windows Script Host.

查看更多
再贱就再见
6楼-- · 2020-06-11 14:32

This is a very outdated thread, many of the answers are incomplete and/or simply don't work. The way to run JS in shell (regardless if you're using windows or not), is to use Node.js. After you have installed Node, you use it from command line, like this:

$ node
> console.log('Hello, world');
Hello, world
undefined
> .exit

or from a file:

$ cat hello.js
#!/usr/bin/node
console.log('Hello, world');

$ ./hello.js
Hello, world

Or from node itself:

$ node hello.js
Hello, world
查看更多
登录 后发表回答