CasperJS: Configure proxy options inside code - javascript

I was wondering how we could set cli parameters inside our code and not by placing them at the end of our command like this:
casperjs casper_tor.js --proxy=127.0.0.1:9050 --proxy-type=socks5
I've tested things like that but it didn't work:
var casper=require('casper').create();
casper.cli.options["proxy"] = "127.0.0.1:9050";
casper.cli.options["proxy-type"] = "socks5";
...
casper.run();
What I'm trying to achieve is to set new proxies inside my code and to scrap my new ip address from whatsmyip.com to check that everything is right (I'm writing bots that will frequently change their proxies).

This is not strictly an answer to your question, but to the more general:
How can I write a single script that will be run by CasperJS using specific CLI options?
There is no clean solution using a single script file, because the "shebang" line #!/bin/... is very limited. In fact, on most OS it only supports a single argument after the interpreter name.
The "proper" solution is of course using more than one script, usually a bash script that will execute your CasperJS script with the proper options.
But...
There is a very old  trick  horrible hack that addresses this problem, the polyglot script. It involves misusing language features to write a file that is a valid script in two (or more) interpreters, doing two different things.
In this case the script will first be read by Bash, because of the shebang line. The script will direct Bash to execute CasperJS with specific options on the script itself and then terminate. CasperJS will skip over the line aimed for Bash and run the rest of the script.
JavaScript version
#!/bin/sh
//bin/true; exec casperjs --proxy=127.0.0.1:8003 test "$0" "$#"
(rest of JavaScript file)
The trick here is that // starts a comment in Javascript, while in Bash it's just part of the first line of code.
CoffeeScript version
#!/bin/sh
""""exec casperjs --proxy=127.0.0.1:8003 test "$0" "$#" #"""
(rest of CoffeeScript file)
The trick here is that """" is skipped over by Bash, because it's just two empty strings, while in CoffeeScript it opens a multiline string that swallows the first line of code.

this works
casper = require('casper').create({
pageSettings: {
proxy: 'http://localhost:3128'
}
});

I needed CasperJS to run inside a node environment. So I have set up Spooky and the good news is that you can set one inside your code like this:
var spooky = new Spooky({
child: {
proxy: '192.128.101.42:9001',
/* ... */
},
/* ... */
},

Related

How to generate JavaScript from a template with terminal similar to Laravel's Artisan?

I have been recently been working with Laravel, and Artisan has several useful make commands that generates php from template stubs on the fly based off a class name, as well as allowing for custom make commands to speed things up.
Short of copy-pasting, there an easy tool that lets me generate plain JS in a similar way based on a templates that allows me to specify some variables to be replaced, then generated in my project?
The ultimate goal of mine for this project is to run a single terminal command with some arguments that generate all the files I need (at least 8-10 PHP files, as well as around 4 JS files), all put into the right directories that lets me do minimal "plugging in" so I can start using them right away. I can chain custom artisan commands, but the next step is getting some kind of terminal JS generator. The nature of the project is that there is approx. 12-14 files that need to be generated and generically filled in before being able to interface with a database table and the front end, so you can understand why I want to do this.
You can do it with bash like this
#!/bin/bash
file_location=path/to/dir/$1.js
if [ -e $1 ]; then
echo "File $1.js already exists!"
else
cat > $file_location <<EOF
let hi = '$2'
console.log(hi)
EOF
fi
$1 is the filename and $2 is another parameter you can pass to the script to be written in the js file.
I would look at hygen. I don't know what your output files are supposed to look like, but hygen allows you to create your own templates and generators. This has a relevant code snippet that displays some JS code. I can't give any advice beyond that as I've not used it thus far.
If this is looking like a bit too much, you can always use VS Code's templates to build up a base, but you won't have any params. A VS Code extension could overcome that I'd guess, but then you're not within a cli.

execute javascript from php

Sorry for this beginner question, I never used js server-side before.
here is my problem:
I have some javascript downloaded from a remote page (it's encrypted, I can't convert it to php), I need to execute it and read its output.
How can I do it? I'm thinking about something like this:
shell_exec('nodejs code...')
but how to pass the code? It's quite long, about 10 lines of javascript.
Another way would be to store the js to a file and run nodejs script.js, but that would be a useless and slow disk IO...
Important caveat about using exec/shell_exec
I feel the need to prepend a caveat about security to this answer. Always be careful when using exec or shell_exec. You almost always should not be taking data over the network to inject into a shell command for security reasons. Writing the script to a file would be much safer because there is no risk of command injection. If you are confident that this approach is required then I strongly advise you to.
Use the PHP function escapeshellcmd which will try to escape shell control characters.
Really ask yourself how much you trust the source? And how much you trust their security?
Having said that. Here's my original answer to the question as asked:
It sounds like the missing piece for your puzzle is the -e parameter for node. This will allow you to pass a script as part of the command invocation.
E.g.
C:\Users\Cmonahan>node -e "console.log('hello world');"
hello world
You can then use PHP exec or shell exec to get the output.
More information:
PHP shell_exec() vs exec()
Node CLI documentation
Edit: Regarding passing multiline arguments to the command line. This can be a bit of a minefield. For example: It depends on whether it is a Unix-like or Windows environment and then, if Unix-like, what shell is parsing the command.
See for example:
Windows: How to specify multiline command on command prompt?
End of line (new line) escapes in bash
I would recommend just making sure the argument is a single line. In the case of JS you can try minification first, which typically strips out all newlines, and see if that works for you.
Here's a popular PHP based minifier https://github.com/mrclay/minify I believe you should be able to install via composer.
dont know am not that at home with php, with isnt it true that php serves html files to the user at home, so why would it be any different from using a javascript file in a normal html page?
cant you just use:<script src="myscripts.js"></script>"
or <script>"with here your script"</script>
in the file that need to load this javascript?

How to develop a javascript library from an already existing npm module (codius)

never done this before.
I'm using https://github.com/codius/codius-host. Codiu§ development has been abandoned, but I want to salvage part of it to use for my own project. I really need to be able to run codius commands from browser, so I need to develop a library or what you call it.
var codius = require('codius')
codius.upload({host: http://contract.host}
codius-host comes packed with command-line integration,
$ CODIUS_HOST=https://codius.host codius upload
How do I make a .js script do what the command-line command does ?
also posted on https://stackoverflow.com/questions/31126511/if-i-have-a-npm-tool-that-uses-comman-line-commands-how-can-i-create-a-javascri
hard time asking this questions since don't know where to start. help.
Assuming that you have access to the codius-host source code you should find the piece of code which manages the command line arguments. I am sure that they do handle the command and the command line arguments from an entry module/function and than later delegate the real job to a different module/function. What you need to do is to provide correct parameters to the functions which the function/module that handles command line argument calls with command line parameters.
In addition to that there are some nodejs libraries that might imitate a command line call from the program itself. One of those I know is shelljs:
https://www.npmjs.com/package/shelljs
You might want to check this out as well. With this one without bothering with the source code you might be able to imitate command line behaviour.

How do I use Jangaroo to convert a single As3 function to javascript?

I've stumbled upon Jangaroo, and it seems to provide what i need. The problem is that to use it the docs say that i need to setup maven.
I really have a single function, so all that is a bit of an overkill.
The ideal solution would be something similar to the Telerik Code Converter(http://converter.telerik.com), but for AS3.
I just updated the documentation on how to use Jangaroo as a command line tool:
https://github.com/CoreMedia/jangaroo-tools/wiki/Stand-Alone-Compiler
After following steps 1 through 6, you can compile your single class like so:
mkdir joo\classes
jooc -v -g SOURCE -classpath %JOOLIBS%\jangaroo-runtime.jar -sourcepath . -d joo\classes GACodec.as
Note that the generated JavaScript file GACodec.js only works together with the jangaroo runtime. The Wiki page continues with instructions on how to end up with a working Webapp. For your class, you just have to unpack jangaroo-runtime.jar:
"%JAVA_HOME%\bin\jar" -xf %JOOLIBS%\jangaroo-runtime.jar
Then, you can run your class from a tiny HTML file that looks like so:
<script src="joo/jangaroo-runtime.module.js"></script>
<script>
joo.classLoader.import_("GACodec");
joo.classLoader.complete(function() {
alert(new GACodec().encode("FOOBAR!"));
});
</script>
When trying out your code, I noticed that it needs a minor change to work: Jangaroo does not generate implicit initialization code for typed local variables. There are at least two lines in your code where an integer variable is declared but not initialized explicitly. ActionScript would set it to 0, but Jangaroo does not. Anyway, it is better style to do explicit initialization, and if you do so, i.e. in your source code replace
var i:int;
by
var i:int = 0;
as far as I can tell, it seems works!
Last thing, I find using Maven easier than installing the Jangaroo SDK, since you just have to install Maven once and it takes care of all needed downloads and makes updating to the latest Jangaroo version a breeze: Just increase the Jangaroo version number in your pom.xml, and Maven takes care of everything else.

Is it possible to execute JSX scripts from outside ExtendScript?

Typically when you're writing a .jsx script to automate an Adobe product (like InDesign, Illustrator or Photoshop), you write, debug and execute the script from the ExtendScript IDE. Is it possible to bypass ExtendScript and run the script from a third program?
I think Adobe products have a built-in JavaScript interpreter which ExtendScript can connect to to access the Adobe object models and automate their software. I'd like to be able to connect directly to that interpreter and run jsx files just as I would in ExtendScript.
Are you on a Mac? If so, you can use AppleScript with the osascript tool to execute your JavaScript. Here are some examples:
Running JSX and Returning a Value
Save this as ~/temp/foo.scpt:
tell application "Adobe Illustrator"
-- 'do javascript' runs any arbitrary JS.
-- We're using the #include feature to run another
-- file. (That's an Adobe extension to JS.)
--
-- You have to pass a full, absolute path to #include.
--
-- The documentation alleges that 'do javascript'
-- can be passed an AppleScript file object, but
-- I wasn't able to get that to work.
do javascript "#include ~/temp/foo.jsx"
end tell
And save this as ~/temp/foo.jsx:
var doc = app.activeDocument;
var numLayers = doc.layers.length;
// The last value in the JSX file will be printed out by
// osascript.
numLayers;
Now, from the command line run osascript ~/temp/foo.scpt It will print the number of layers in the active Illustrator document.
Getting data out of the JavaScript is limiting. You can't print to stdout from within the JavaScript. Instead, place the value you want to return as the last statement of the JSX file; it will be printed by osascript. (Here's why: The last value in the JSX file is the return value of the do javascript AppleScript statement. That is also the last value in the AppleScript file, and osascript prints the final value.)
The value you return from JavaScript can be a number, a string, an array, or anything else that retains its value when converted to a string. If you want to return a complex object, you'll need to #include a JSON library and call .toJSONString() on the object.
Passing Arguments to JSX
To pass arguments to the JSX code, follow this example:
File ~/temp/args.scpt:
on run argv
tell application "Adobe Illustrator"
set js to "#include '~/temp/args.jsx';" & return
set js to js & "main(arguments);" & return
do javascript js with arguments argv
end tell
end run
File ~/temp/args.jsx
function main(argv) {
var layer = app.activeDocument.activeLayer;
app.defaultStroked = true;
app.defaultFilled = true;
// Top, left, width, height (in points).
// Note that parameters start at argv[0].
layer.pathItems.rectangle(argv[0], argv[1], argv[2], argv[3]);
}
And then run osascript args.scpt 50 30 10 80
Debugging
The do javascript command also has options for launching the ExtendScript debugger. For details, open the Illustrator dictionary in AppleScript Editor.
For Windows users, you can use a vbs script. Pass arguments to the .jsx script by providing arguments to the cscript command like so: cscript test.vbs "hello". test.vbs could look like so:
Dim appRef
Dim javaScriptFile
Dim argsArr()
Dim fsObj : Set fsObj = CreateObject("Scripting.FileSystemObject")
Dim jsxFile : Set jsxFile = fsObj.OpenTextFile("C:\Users\path\test.jsx", 1, False)
Dim fileContents : fileContents = jsxFile.ReadAll
jsxFile.Close
Set jsxFile = Nothing
Set fsObj = Nothing
javascriptFile = fileContents & "main(arguments);"
Set appRef = CreateObject("Illustrator.Application")
ReDim argsArr(Wscript.Arguments.length-1)
For i = 0 To Wscript.Arguments.length-1
argsArr(i) = Wscript.Arguments(i)
Next
Wscript.Echo appRef.DoJavaScript(javascriptFile, argsArr, 1)
The Wscript.Echo will return the last line returned by the .jsx file. A .jsx file example could be:
function main(argv) {
alert(argv[0]);
return "test";
}
When ran, you should seee Illustrator (or whatever adobe program) alert "hello" and then "test" will be returned to stdout (you should see it in the command prompt window).
This works in windows:
"C:\Program Files (x86)\Adobe\Adobe Photoshop CS5\Photoshop.exe" C:\completepathto\my.jsx
Pay attention to the path to Photoshop. It must be quoted since it contains spaces.
There are plenty of tricks for figuring out where Photoshop is loaded. Here is one that finds every location where Photoshop has been loaded and places those in x.lst
#REM The Presets\Scripts doesn't really restrict where the loop is looking,
#REM thus the "IF EXIST" is needed. The FIND makes sure that the
#for /R "%ProgramFiles(x86)%\Adobe" %%f in (Presets\Scripts)
DO #IF EXIST %%f
(echo %%f | FIND /I "Adobe Photoshop C" >> x.lst )
You can then process each line in x.lst. NOTE: The entire "#for" should be on ONE line, I split it to multiple lines for readability.
If you believe there will be only one Photoshop (and not Elements) then you could change
"echo %%f"
to
"%%f\..\..\Photoshop.exe" C:\completepathto\my.jsx
The straight answer is YES. Illustrator, InDesign and Photoshop can all be scripted through COM. Any program that you make that can access COM (such as a .net language, C++, BCX, Autohotkey or Powerpro) can tell Illustrator, InDesign or Photoshop to do things.
Here is an example for Powerpro(you will need powerpro's com plugin), and this works in CS4 and CS5:
Function ComLoad() ;;MAKE SURE TO CALL .#ComUnload WHEN EXITING FUNCTION CALLS!
static objname="Illustrator.Application"
static com_status, com_type
static appRef=com.create_object(objname)
endfunction
Function ComUnload();;this is end the com calls and unload com
com.unload
endfunction
After you use the ComLoad() function, you then run any kind of method or function offered by the COM library. Here is how to use Powerpro to tell Illustrator to run your jsx or js file:
;Run a script from anywhere
Function RunOtherScript(whatscript)
If (file.Validpath(whatscript) == 0)do
messagebox("ok","Whoops! That script doesn't exist!","ILL Runscript")
quit
endif
.#ComLoad()
appRef.DoJavaScriptFile(whatscript)
.#ComUnload()
quit
Here is an image of a floating toolbar that I made using Powerpro. The buttons are all attached to com functions. Most of the time I use the com functions to run external jsx scripts.
[edit]
There is another way! You can use the Adobe Configurator to create new panels which are capable of launching scripts. You can design the panel in any way you like, and the results are quite similar in effect to the powerpro toolbar I've described above. In fact, I moved from the powerpro toolbar to an Adobe Configurator Panel.
If you place the .jsx files in the right location
Photoshop
folder location:
/Applications/Adobe\ Photoshop\ CS5/Presets/Scripts
menu location:
File > Scripts
Illustrator
folder location:
/Applications/Adobe\ Illustrator\ CS5/Presets.localized/en_GB/Scripts
menu location:
File > Scripts
InDesign
folder location:
/Users/{user}/Library/Preferences/Adobe\ InDesign/Version\ 7.0/en_GB/Scripts/Scripts\ Panel
menu location:
Window > Utilities > Scripts
These are the paths on OSX, it should be easy to find the equivalent on Windows for Photoshop and Illustrator, but for InDesign it might be easier to open the Scripts Panel and open the scripts folder using the Panel's context menu.
I know that you can run .jsfl scripts from the command line by opening Flash and passing the path to the .jsfl script as an argument, but that doesn't seem to work for .jsx files with InDesign.
HTH
This question is quite old. I am going to answer this on the assumption that:
You're running JSX scripts for after effects.
You're using Windows.
I'm not sure whether you want to pass arguments to a script (in which case my simple solution won't work, or might need nasty workarounds).
Fortunately there is an easy way to do this with after effects. You can launch cmd and type the following command:
afterfx -r C:/Users/me/myscript.jsx
If afterfx isn't recognized, you'll need to add the after effects installation path to Path in your System Variables. I'm not aware of the availability of this feature in other Adobe programs.
For more information about running your after effects scripts from the command line, you can consult: https://helpx.adobe.com/after-effects/using/scripts.html
You can use extend script to run it .
there is a free extension on creative cloud will help you to run scripts fast in illustrator , aftereffects, photoshop and premiere pro
you can find it on adobe exchange ( liveview )

Categories

Resources