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?
Related
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.
I have a program that logs every GET/POST request made by a website during the page load process. I want to go through these requests one by one, execute them, and then determine if the file that was returned is a Javascript. Given that it won't have a .js ending (because of scripts like this, yanked from google.com a minute ago), how can I parse the file gotten from the request and identify if it is a Javascript file?
Thanks!
EDIT:
It is better to get a false positive than a false negative. That is, I would rather have some non-JS included in the JS-list than cut some real JS from the list.
The javascript link that you referred does not have a content type, nor does it have the js extension.
Any text file can be considered javascript if it can get executed which can make detection from scratch very difficult. There are two methods that come to mind.
Run a linter on the file contents. If the error is a syntax error or a Parsing error, it is not javascript. If there are no syntax error or parsing error, it should be considered javascript
Parse the AST (Abstract syntax tree) for the file contents. A javascript file would parse without errors. There should be a number of AST libraries available. I haven't worked with JS AST, so can't recommend any one of them but a quick search should give you some options.
I am not sure but probably a linter would also run AST before doing syntax checks. In this case, running AST seems like a lighter option.
The easiest way would be to check if there was anything identifying javascript files by their URI, because the alternatives are a lot heavier. But since you said this isn't an option, you can always check the syntax of the contents of each file using some heuristic tool. You can also check the response headers for its content-type.
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.
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',
/* ... */
},
/* ... */
},
I try to get to a page straight from Bash at http://www.ocwconsortium.org/. The page appears when you write mathematics to the field at the top right corner. I tested
open http://www.ocwconsortium.org/#mathematics
but it leads to the main page. It is clearly some javascript thing. How can I get the results straight from Bash on the first page?
[Clarification]
Let's take an example. I have the following lines for a Math search engine in .bashrc:
alias mathundergradsearch='/Users/user/bin/mathundergraduate'
Things in a separate file:
#!/bin/sh
q=$1
w=$2
e=$3
r=$4
t=$5
open "http://www.google.com/cse?cx=007883453237583604479%3A1qd7hky6khe&ie=UTF-8&q=$q+$w+$e+$r+$t&hl=en"
Now, I want something similar to the example. The difference is that the other site contains javascript or something that does not allow me to see the parameters. How could I know where to put the search parameters as I cannot see the details?
open "http://www.ocwconsortium.org/index.php?q=mathematics&option=com_coursefinder&uss=1&l=&s=&Itemid=166&b.x=0&b.y=0&b=search"
You need quotes because the URL contains characters the shell considers to be special.
The Links web browser more or less runs from the commandline (like lynx) and supports basic javascript.
Even though the title of the post sounds general, your question is very specific. It's unclear to me what you're trying to achieve in the end. Clearly you can access sites that rely heavily on javascript (else you wouldn't be able to post your question here), so I'm sure that you can open the mentioned site in a normal browser.
If you just want to execute javascript from the commandline (as the title suggests), it's easy if you're running bash via cygwin. You just call cscript.exe and provide a .js scriptname of what you wish to execute.
I didn't get anything handled by JavaScript - it just took me to
http://www.ocwconsortium.org/index.php?q=mathematics&option=com_coursefinder&uss=1&l=&s=&Itemid=166&b.x=0&b.y=0&b=search
Replacing mathematics (right after q=) should work. You may be able to strip out some of that query string, but I tried a couple of things and and it didn't play nice.
Don't forget to encode your query for URLs.
You will need to parse the response, find the URL that is being opened via JavaScript and then open that URL.
Check this out: http://www.phantomjs.org/.
PhantomJS it's a CLI tool that runs a real, fully-fledged Browser without the Chrome.