0

I have gone through multiple post like Embedded js in a batch file which suggest the possibility of combining batch file and javascript. My question here is-whether it is possible to use the method of a .js file in .bat file? For example-Define a js file with some methods as below -

test.js

add:function(a, b){ return a+b;}

test.bat

add(1, 2); ::Or something like add 1 2

Output

C:\>test

3

Community
  • 1
  • 1
Gaurav B
  • 160
  • 8

2 Answers2

0

something like this (it's a verbose but this is what I can come up with)? And this will not work with javascript but with jscript and jscript.net (but reqiores a little bit different code)

@if (@X)==(@Y) @end /* JScript comment
    @echo off

    call :add 1 2
    call :subst 5 2

    exit /b %errorlevel%
    :add [ a , b ]
        cscript //E:JScript //nologo "%~f0" add %~1 %~2 
    exit /b %errorlevel%

    :subst [ a , b ]
        cscript //E:JScript //nologo "%~f0" subst %~1 %~2 
    exit /b %errorlevel%






@if (@X)==(@Y) @end JScript comment */

var ARGS = WScript.Arguments;



function subst(a,b){
    WScript.Echo(a - b);
}

function add(a,b){
    WScript.Echo(a + b);
}

switch(ARGS.Item(0).toLowerCase()){
  case "subst":
    subst(ARGS.Item(1),ARGS.Item(2));
    break;
  case "add":
    add(ARGS.Item(1),ARGS.Item(2));
    break;
  default:
    WScript.Echo("wrong function");
    WScript.Quit(1);

}
npocmaka
  • 55,367
  • 18
  • 148
  • 187
0

There are several ways to do that. The method below is a very simple one:

test.js

function add(a, b){ return a+b;}
function sub(a, b){ return a-b;}

WScript.Echo(eval(WScript.Arguments(0)));

test.bat

@echo off

set eval=cscript //nologo test.js 

%eval% add(1,2)
%eval% sub(1,2)

Output

C:\> test
3
-1

In this case, the expression after the %eval% can not contain spaces nor special characters. To do that, just enclose the expression in quotes:

%eval% "add(1,2) * 4 + sub(1,2)"
Aacini
  • 65,180
  • 12
  • 72
  • 108
  • Thanks Aachini for providing the simple method of doing the job. But just wondering if it is possible to have direct access to a particular js function like how 'mocha' do. – Gaurav B Feb 10 '15 at 10:12
  • Currently I am using mocha to test my js method functionality, but want to execute those methods directly from command line. – Gaurav B Feb 10 '15 at 10:14