简体   繁体   中英

How to run shell command from javascript client-side?

I have the simplest program: 1 HTML file, 1 CSS file, and 1 JS file, just run directly on my own computer. And all I'm trying to do is that when you press a button in the program , one single shell command (Windows) is run directly on the computer. This will generate file, which in turn will be used further inside the program.

It appears you cannot access your local files through JS alone, so I installed NodeJS (which is completely new to me). But I still can't get it to work that way either.

The only way I finally got NodeJS to host the HTML page in a way that the JS and CSS files also work, is by copying the code I got here: https://stackoverflow.com/a/13635318 . (I called it server.js ).

But I still haven't been able to find a way to call upon server.js while client-sided to run that shell command. Some posts suggest using AJAX for this, like here https://stackoverflow.com/a/53897335 , but I haven't been able to find any way to successfully catch that in server.js .

I figured out how do it in another roundabout way:

With Django you can easily combine JS and Python, and Python can run shell commands much more easily.


In case someone wants the exact code:

Python (views.py):

import subprocess

def home(request):
    if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
        subprocess.call(["ls", "-l"])
    return render(request, 'index.html')

Javascript:

function toView() {
    var csrftoken = $("[name=csrfmiddlewaretoken]").val();
    $.ajax({
        method: 'POST',
        url: '',
        headers:{
            "X-CSRFToken": csrftoken
        },
        data: {},
        success: function (data) {
             alert("it worked!");
        },
        error: function (data) {
             alert("it didnt work");
        }
    });
}

HTML (index.html):

        <form method="post">
             {% csrf_token %}
            <button type="button" onclick="toView()">Do x</button>
        </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM