15

I need to list all the files in the javascript such as "ls"??

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
Ambika
  • 335
  • 2
  • 3
  • 8

6 Answers6

19

Please give more information of your environment.

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()

Hendrik Brummermann
  • 8,242
  • 3
  • 31
  • 55
  • I suppose this is going to run on a server. What about pure JavaScript to run on the client? Just for security testing. – Maf Jun 22 '23 at 09:48
7

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

JohnP
  • 49,507
  • 13
  • 108
  • 140
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.

baudot
  • 1,618
  • 20
  • 33
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.

Kumar
  • 5,038
  • 7
  • 39
  • 51
  • 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? – Maf Jun 22 '23 at 09:52
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.

Atanas Korchev
  • 30,562
  • 8
  • 59
  • 93
  • Related conversation: http://stackoverflow.com/questions/41088671/asp-net-c-sharp-mvc-website-how-can-i-mount-a-drive-upon-button-click – gunslingor Dec 12 '16 at 00:44
0

I'd like to add an answer 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 Ventura)

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

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

This will show all the STDOUT, STDERR, etc, on screen, as if it is a command typed into a shell. This is the docs.

nonopolarity
  • 146,324
  • 131
  • 460
  • 740