15

I need to list all the files in the JavaScript thingy, such as using "ls".

1
  • 3
    You are talking about executing commands server-side, correct? Not on the client browser? Commented Oct 6, 2012 at 19:58

6 Answers 6

19

Unprivileged JavaScript in a browser can neither list files nor execute programs for security reasons.

In Node.js, for example, executing programs works like this:

var spawn = require('child_process').spawn,
var ls  = spawn('ls', ['-l']);
ls.stdout.on('data', function (data) {
   console.log(data);
});

And there is a direct way to list files using readdir().

Sign up to request clarification or add additional context in comments.

1 Comment

I suppose this is going to run on a server. What about pure JavaScript to run on the client? Just for security testing.
7

You can't run system commands on the client with JavaScript since it works inside a browser sandbox. You'd need to use some other client-side tech like Flash, ActiveX or maybe applets.

1 Comment

I think Applets also run in a sandbox.
5

An even easier way in node.js is:

var fs = require('fs');
var ls = fs.readdirSync('/usr');

The variable ls now contains an array with the filenames at /usr.

Comments

3

The short answer is: you should not do this as it opens a huge attack vector against your application. Imagine someone running "rm -rf" :).

If you must do this and you are 1000% sure you allow only a few commands which cannot cause any harm you can call a server page using Ajax. That page could run the specified command and return response. Again I emphasize this is a huge security risk and should better not be done.

1 Comment

3

AFAIK, you can not run any system command. This will violate the security model. You can do send a print command, but I wonder anything beyond that is possible.

1 Comment

Is that an heresy to say that if someone can access the stdout then somehow other system calls also could be invoked after passing some security barrier?
0

If you'd like the program you run give out output that uses ANSI escape sequences (for example, to print out the progress percentage on the screen):

I wasn't able to do that on macOS unless I use the following (I am using macOS v13 (Ventura)):

const { spawn } = require("node:child_process");

const commandProcess = spawn(
  "node",
  ["someScript.js", "someArg1", "someArg2"],
  {
    stdio: "inherit"
  }
);

This will show all the standard output, standard error, etc., on screen, as if it is a command typed into a shell. This is the documentation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.