11

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

mattytommo
  • 52,879
  • 15
  • 115
  • 143
theschmitzer
  • 10,928
  • 11
  • 37
  • 48

5 Answers5

17

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.

brianary
  • 7,906
  • 2
  • 33
  • 29
6

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

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

Nate Zaugg
  • 4,041
  • 2
  • 34
  • 50
  • It's so funny... this question was asked before NodeJS was even a thing. :') Had no idea what the accepted answer was talking about until I saw the date. How times change... –  Feb 16 '16 at 10:38
4

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

spoulson
  • 20,523
  • 14
  • 72
  • 101
3

Try WScript:

WScript.Echo('hello world');
Joel Coehoorn
  • 362,140
  • 107
  • 528
  • 764
0

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
not2qubit
  • 10,014
  • 4
  • 72
  • 101
  • While it's old and the documentation is more sparse by the day, a lot can be accomplished on a Windows machine by scripts written using WSH + JScript, including compiling to a small, portable executable file. Node.js + NPM have Win32 libraries and can probably accomplish all of the same end goals, but there will certainly be a difference in the "weights" of the solution. The Windows Node.js executable alone was about 50mb at the time of writing this comment. – Aaron Cicali Aug 04 '20 at 23:07