Is ther any way to execute javascript from a .bat file or embed the javascript in .bat file.
I need a javascript code to write/read to a file in a local folder.This javascript i should be able to execute it using a .bat.
Is it possible?.
Thanks
SNA
Follow these two steps to run Javascript in a Windows batch file, either .BAT or .CMD.
First step: add these lines to the beginning of your file
#set #junk=1 /*
#echo off
cscript //nologo //E:jscript %0 %*
goto :eof
*/
Second step: write your Javascript to only use objects that are available in Windows Scripting Host, i.e. use Wscript.Echo() to print output on the standard output.
Here is a complete example ready to run by typing calen 2011 02
#set #junk=1 /*
#echo off
cscript //nologo //E:jscript %0 %*
goto :eof
*/
x = WScript.Arguments
Yr = x(0) ; Mo = x(1)
YS = "JanFebMarAprMayJunJulAugSepOctNovDec"
MN = Mo<1 || Mo>12 ? Mo : YS.substr(3*Mo-3, 3) // Month Name
WScript.echo(" ", Yr, " ", MN)
WScript.echo(" Mo Tu We Th Fr Sa Su")
WD = new Date(Yr, Mo-1, 1).getDay() ;
if (WD==0) WD = 7 // Week Day Number of 1st
LD = new Date(Yr, Mo, 0).getDate() // Last Day of month
Wk = "" ; for (D=1 ; D < WD ; D++) Wk += " "
for (D=1 ; D<=LD ; D++) {
Wk = Wk + " " + (D<10 ? "0"+D : D) ; WD++
if ((WD==8) || (D==LD)) { WScript.echo(Wk) ; WD = WD-7 ; Wk = "" }
}
WScript.echo(" ------ ")
Just put this in calen.bat or calen.cmd and run it on any reasonably recent Windows.
Never struggle with another convoluted batch file again.
I know I am a bit late to this, but if you have node.js installed on your system you can use the bat file to call in a node function and execute your javascript code.
https://nodejs.org/en/
Node.js (when using modules) lets you do quite a few things bat files can do. Using only javascript you can edit/phrase local files, run exe files ect... ect..
A step by step guide to setting this up would be:
1) download and install node.js https://nodejs.org/en/download/
2) Create a javascript file on your computer with the js code you want to run.
In this file you will add the code to allow node.js to access local files on your machine. Put the below code at the top of your javascript file:
//Load required modules
fs = require('fs')
//Function to read local files
fs.readFile('path-to-file/this-is-my-file.txt', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
//data is the text file
}
3) create a bat file like this:
echo off
node "path-to-javascript\index.js"
And you're all setup!
Depends on which javascript you mean. You have few options - all the scripts bellow should be saved with .bat extension:
1) JScript that comes with csript.exe:
#if (#X) == (#Y) #end /*
#cscript //E:JScript //nologo "%~f0" "%*"
#exit /b %errorlevel%
*/
WScript.StdOut.WriteLine("Echo from cscript's javascript");
2) javascript that comes with HTA/IExplorer (which allows you also to use UI elements and access to the local file system):
<!-- :
#echo off
mshta.exe "%~f0"
exit /b %errorlevel%
-->
<html>
<head>
<title>~~~~</title>
<!--meta http-equiv="X-UA-Compatible" content="IE=edge"-->
</head>
<body>
<font size="15"><b>Hello from HTA's javascript</b></font>
<script type="text/javascript">
setTimeout(function() {
document.body.innerHTML=document.body.innerHTML + "<p/><p><font size='7'>Hello from HTA's javascript</font></p>";;
}, 2000);
</script>
</body>
</html>
3) JSCrip.NET - may be most powerfull option as gives you access to the .NET framework (though it creates a small .exe file):
#if (#X)==(#Y) #end /* JScript comment
#echo off
setlocal
for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
set "jsc=%%v"
)
if not exist "%~n0.exe" (
"%jsc%" /nologo /out:"%~n0.exe" "%~dpsfnx0"
)
%~n0.exe %*
endlocal & exit /b %errorlevel%
*/
import System;
Console.Write("Echo from .NET")
There are ways to use it without creating this exe file ,but this is the most readable way according to me.
4) If you are aming NODE.JS there's also a way:
0</* ::
#echo off
echo hello from batch
node "%~f0" %*
exit /b %errorlevel%
*/0;
console.log('Hello from Node');
on Windows, in a batch file, try
cscript jsfile.js
You can run a JScript script from a batch-file with the command-line based scripting host CScript.exe.
You would need the script in a separate file though which you pass as an argument to CScript.exe. If you want to keep everything in a sinle file, you can embed the JScript code in you batch-file, dump it to a temporary file which you pass to CScript.exe and delete the temporary script file afterwards.
There might be more elegant solutions (hopefully)
It is, sort of. On Windows only, of course.
That said, there is probably a better way to do this. What do you need the JavaScript to do? Why does it have to be JavaScript?
Short answer: no.
Javascript (when run from a browser) can't access the client resources (this is by design, to avoid security risks).
You can use Javascript outside of the browser, to create scripts, but you should provide more details on what you are trying to do (and what Operative System you expect to run this on).
Also, check this page for more details.
You can run a JScript script from a batch-file with the command-line based scripting host CScript.exe.
You would need the script in a separate file though which you pass as an argument to CScript.exe. If you want to keep everything in a single file, you can embed the JScript code in you batch-file, dump it to a temporary file which you pass to CScript.exe and delete the temporary script file afterwards.
There might be more elegant solutions (hopefully)
Related
I have an application (IP2SI2IP.exe ) and I wrote this command in JS to run it :
<script type="text/javascript">
function run(){
wshShell=new ActiveXObject("Wscript.shell"
);
wshShell.Run("C:/Windows/System32/cmd.exe",1,false)
wshShell.Run("IP2SI2IP /S /N xxx.SES",1,false)
}
</script>
This app converts the specific file with SES extension (for example : xxx.SES ) IP unit to SI unit. Anytime when I have a new input file (for example yyy.SES), I have to re-type it manually in front of the IP2SI2IP /S /N command the run it again.
I'm looking for another command that it can first: find the file with SES extension from the related folder then puts this SES file in front of the "IP2SI2IP /S /N" command and run it by itself.
Thanks!
I'm calling an Applescript scpt file and when I opened the AppleScript editor it had an option to use JavaScript.
I would like to convert my AppleScript to JavaScript but can't find any documentation on it (announcements and such and redirects on apple).
Here is my AppleScript:
#!/usr/bin/osascript
on run argv
set output to "{\"1st Parameter\":\"" & first item of argv & "\"}"
return output
end run
More context:
I'm trying to loop through a directory and export from Excel. I only need to know about how to run JavaScript in a SCPT file but this is the background.
#!/usr/bin/osascript
on run argv
#goal is to export multiple files to csv
#the plan is to
#pass in folder and loop through files or
#pass in array of files (paths as a comma separated string)
#pass in single file and call script multiple times
set processReportsScript to "excel -e '" & first item of argv & "' '" -o '" & second item of argv & "'.csv'"
do shell script processReportsScript
end run
UPDATE:
While in Script Editor I'm able to run this JavaScript:
function run(args) {
var x = false;
var y = Application("Mail");
var running = y.running();
var id = y.id();
debugger;
if (x) {
console.log("Why isn't this being called?")
}
return "hello";
}
Based in part on this guide.
However when I save the JavaScript into the SCPT file and call it from an external application it gives the following error:
script error: Expected end of line, etc. but found “(”. (-2741)
It does not give any errors when using AppleScript.
FYI the external application is passing the script to osascript.
UPDATE 2:
I changed the extension from scpt to js and now it's running. I read that it's possible to pass in the language type using -l but when I do I get numerous variations of the error:
no such component " 'JavaScript'"
no such component " JavaScript"
As long as it works by changing the extension I think this works.
Both AppleScript and JavaScript for Automation (JXA) use the same file extension: ".scpt". When you are in the Script Editor, there is a language popup where you can select either:
The is no tool for auto-conversion from AppleScript to JXA.
For more info about JXA, see
JXA Resources
hello friend i am making an aplication based on web plataform html5 css3 ...
and i have a web site with this, but i thought creat a direct link to shout(pop) this aplication to end user from the desktop.
example:
Descarga Aplicativo
but it not work on chrome or other browser. i get error file or uncomplete download. file named: IcarosNetWeb.downkload ....
Can someone help me with this?
Solved by this way
Direct Access
As not able to find the way to do it directly. I created a free mechanism:
1. Create a .bat file (Batch command line) Hiden.(This is the task: create the shortcut to the application with its parameters.)
Compressing the .bat file within a file self-extracting WinRAR and run the .bat file at the end of the extraction, automatically.
Create Hidden Log File on C:/ if have problem executing.
AutoInstall.bat file
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET LinkName=MyAplication
SET Esc_LinkDest=%%HOMEDRIVE%%%%HOMEPATH%%\Desktop\!LinkName!.lnk
SET Esc_LinkTarget=%%ProgramFiles(x86)%%\Google\Chrome\Application\chrome.exe
SET Esc_WorkDir=%%ProgramFiles(x86)%%\Google\Chrome\Application
SET Esc_Icon=%%ProgramFiles(x86)%%\Google\Chrome\Application\chrome.exe,6
SET Esc_URL=www.google.com
SET Esc_ARG=--app=http://!Esc_URL!/
SET cSctVBS=CreateShortcut.vbs
SET LOG=".\%~N0_runtime.log"
((
echo Set oWS = WScript.CreateObject^("WScript.Shell"^)
echo sLinkFile = oWS.ExpandEnvironmentStrings^("!Esc_LinkDest!"^)
echo Set oLink = oWS.CreateShortcut^(sLinkFile^)
echo oLink.TargetPath = oWS.ExpandEnvironmentStrings^("!Esc_LinkTarget!"^)
echo oLink.WindowStyle = 1
echo oLink.IconLocation = oWS.ExpandEnvironmentStrings^("!Esc_Icon!"^)
echo oLink.Arguments = !Esc_URL!
echo oLink.WorkingDirectory = oWS.ExpandEnvironmentStrings^("!Esc_WorkDir!"^)
echo oLink.Description = "Internet Access"
echo oLink.Save
)1>!cSctVBS!
cscript //nologo .\!cSctVBS!
DEL !cSctVBS! /f /q
)1>> !LOG! 2>>&1
attrib +h !LOG!
in Winrar:
put SFX File option, go Advance Tab and Click SFX FIle, on tab General add folder Extraction C:/ and on Instaltion tab in Instaltion after Extraction field add the full name (no path) .bat aplication.
My requirement is I need to check whether Chrome browser is insatlled on the client machine or not using Javascript. I have searched on the net not able to find the way out.
Please help in getting this done.
You can't do that with JavaScript, and even if you could, you shouldn't.
JavaScript on the client doesn't have access to the user's system, for very good reasons. (Think, servers with bad intentions.)
You can check if the browser is Chrome with the next code
if(!window.chrome){
//Chrome code
}else{
// Chrome block
}
You can't. Not with JavaScript. However, you can check whether the browser that is currently being used to view your webpage is Google Chrome or not.
<script type="text/javascript">
if(window.chrome){
document.write("Browser is Chrome");
}
else{
document.write("Please download Chrome");
}
</script>
You can't get that kind of information directly from javascript.
What you can do is use that PowerShell command in a script and save the result in a file that you'll read later using javascript.
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, InstallLocation, Publisher, InstallDate | Format-Table -AutoSize
This will get you all the installed programs on the machine from the HKEY_LOCAL_MACHINE registry folder.
The exact path to the folder from wich the informations are retrieved is : HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\
The given command will display you the application name followed by it's version, it's install location, publisher name and installation date in a PowerShell terminal.
If you want to output that list in a file simply add >FileName.txt after the command before pressing enter.
Note that by default the file will be created in the C:\Users\YourUserName\ folder so if you want the file to be created in a specific location you'll have to use the CD command to get to that specific location before executing the Get-Item-Property command.
This will get you done for the get installed programs on a machine part.
Now we can get into the check if app x is installed on the machine part.
First load the previously generated file in your js application you will use it's content to determine if an application is installed on the computer.
The faster way to get if 'chrome' is installed will be to load the file as a string and then do that basic stuff :
if (string.includes('chrome') == true) {
// chrome is installed on the machine
// you can do some more stuff
// like extracting it's path from the file content
} else {
console.log('error: chrome is not installed on this computer');
}
Needless to say that this will only work if used on the same computer from which you want to check the installed applications.
Edit: If you want a more practical file to use in javascript you can replace
Format-Table -AutoSize >FileName.txt
with :
Export-Csv -path .\FileName.txt -NoTypeInformation
this way you can split your file lines using the string.split(',') method and don't have to do some extra stuff to deal with the spaces between data.
Edit 2:
Here's a full working implementation that will let you retrieve informations from a PowerShell script directly from your javascript using NodeJs.
get_programs.ps1 (PowerShell script file) :
chcp 65001 # sets the encoding for displaying chars correctly
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, InstallLocation | ConvertTo-Csv -NoTypeInformation
chcp 850 # restores the default encoding set this will avoid police changes due to the terminal modifications
Notice the change at the end of the command which is now:
| ConvertTo-Csv -NoTypeInformation
this allows to log data in the PowerShell terminal in the csv format which will simplify it's parsing as a string.
If you don't want to use another file to hold those few PowerShell
commands you can use this
child = spawn("powershell.exe",[`chcp 65001
Get-ItemProperty HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* | Select-Object DisplayName, DisplayVersion, InstallLocation | ConvertTo-Csv -NoTypeInformation
chcp 850`]);
as a replacement for
child = spawn("powershell.exe",["./get_programs.ps1"]);
If you choose to do this don't forget to escape the \ chars else it will not work.
app.js :
var spawn = require("child_process").spawn,child;
child = spawn("powershell.exe",["./get_programs.ps1"]); // here we start our PowerShell script "./" means that it's in the same directory as the .js file
let chromeDetails;
child.stdout.on("data", (data) => { // data event
// here we receive each outputed line in the PowerShell terminal as an Uint8Array
if (data.includes('Chrome')) { // check for the 'Chrome' string in data
chromeDetails = data.toString(); // adds data converted as string
}
});
child.stderr.on("data", (data) => { // logs errors
console.log(`Powershell Errors: ${data}`);
});
child.on("exit", () => { // exit event
console.log("Powershell Script finished");
if (chromeDetails != undefined) {
console.log(`> chrome has been detected on this computer
available informations (appName, version, installPath):
${chromeDetails}`);
} else
console.log('> chrome has not been detected on this computer');
});
child.stdin.end(); // we end the child
Expected output :
Powershell Script finished
> chrome has been detected on this computer
available informations (appName, version, installPath):
"Google Chrome","103.0.5060.114","C:\Program Files\Google\Chrome\Application"
If you are not on Windows you may want to take a look at Spawning .bat and .cmd files on Windows from the NodeJs documentation to get hints on how to adapt the above app.js code to work on your system.
I am watching one of Jim Weirich's presentations about Y combinator using JavaScript in Emacs, at http://v.youku.com/v_show/id_XNDQ4NDY0NjM2.html
(The presentation is pretty much similar, I think, to what he gave at RubyConf 2012 using Ruby instead of javascript ..http://confreaks.com/videos/1287-rubyconf2012-y-not-adventures-in-functional-programming)
One thing I noticed that he was evaluating JS in the buffer from within Emacs (by node.js, as some of the error msgs shown) via "C-c v" short-cut, and also got the output back into another buffer.
I am wondering is there a simple instruction (before diving into comint/call-process details) on how to get that setup on latest Emacs on windows...I searched, but so far no success. Btw, I alreay get node.exe installed, and can get node interactively run as a REPL in Emacs by "M-x run-js", following instruction at in an article "setting-up-emacs-as-a-javascript-editing-environment-for-fun-and-profit" (sorry not able to post more than 2 links...)
Thanks,
/bruin
I defined the following function and its key map. So far it works.
(defun node-js-eval-region-or-buffer ()
"Evaluate the current buffer (or region if mark-active),
and return the result into another buffer,
which is to be shown in a window."
(interactive)
(let ((debug-on-error t) (start 1) (end 1))
(cond
(mark-active
(setq start (point))
(setq end (mark)))
(t
(setq start (point-min))
(setq end (point-max))))
(call-process-region
start end ; seems the order does not matter
"node" ; node.js
nil ; don't delete region
"node.js" ; output buffer
nil) ; no redisply during output
(message "Region or buffer evaluated!")
(setq deactivate-mark t))) ; deactive the region, regardless
(define-key global-map (kbd "C-c v") 'node-js-eval-region-or-buffer)
I still have another thing to dig a bit: how to automatically split the screen to show the output buffer? I guess it should be not too difficult...
Btw, I install Git and Node.js for Windows, and copy "node.exe" into Git's "/bin" directory (which has been added to PATH environment during installation).
install js3-mode
then:
(require 'js-comint)
(setq inferior-js-program-command "node --interactive")
(setenv "NODE_NO_READLINE" "1")
;; Use your favorited js mode here:
(add-hook 'js3-mode-hook '(lambda ()
(local-set-key "\C-x\C-e"
'js-send-last-sexp)
(local-set-key "\C-\M-x"
'js-send-last-sexp-and-go)
(local-set-key "\C-cb"
'js-send-buffer)
(local-set-key "\C-c\C-b"
'js-send-buffer-and-go)
(local-set-key "\C-cl"
'js-load-file-and-go)
))