0

I have got a task where I have a js file where I shall use nodejs and the exec() command to list all files in the current directory I am in. I do not know the name of the current directory. How do I write the exec() and ls command in the js file to be able to get a list of the files?

Can anyone in an east way tell me of to write that piece of code?

Daemon Painter
  • 3,208
  • 3
  • 29
  • 44
Gabriella
  • 1
  • 1
  • 1
  • 1
    Does this answer your question? [node.js fs.readdir recursive directory search](https://stackoverflow.com/questions/5827612/node-js-fs-readdir-recursive-directory-search) – Manuel Spigolon Dec 10 '20 at 11:59

1 Answers1

3

That should be fine. The module 'util' is to promisify exec(), for it to return a promise, then you await it, and can use it.

    const util = require('util')
    const exec = util.promisify(require('child_process').exec)
    
    const main = async() => {
            const { stdout, stderr } = await exec('ls', ['a', '-l' ])
            if (stderr) {
                    console.log(stderr)
            }   
            console.log(`the list of files in this directory is: ${stdout}`)
    }
    main()

exec (spawn and fork as well) are fork process (child process) from the main node process (mother process), means that they run on a concurrent process, detached from the mother one. It's very efficient as they use another thread of the processor.

In the case of exec, it open a new terminal (tty) and run on it, so the command exec('ls', ['a','-l'}) is running 'ls -l' cmd in a shell (i don t know why the 'a'). Because this exec child-process is running into a shell, any shell command can be executed: I could have done await exec('find . -type f | wc -l') return the number of files, or await exec('cat fileName.js') (print out the content of fileName in the terminal) return the content of fileName.js into stdout.

Exec return a call-back with (err, stdout, stderr), for this snippet to be more clear, here util.promisify() promisify the call-back and then we can use async/await or .then().catch(). We also could have done:

const util = require('util')
const { exec } = require('child_process')        
const ex = util.promisify(exec)
const main = async() => {
                const { stdout, stderr } = await ex('ls')
                if (stderr)...

In fact more basically this code could be written like this

const { exec } = require('child_process');
exec('ls', (error, stdout, stderr) => {
  if (error) {
          console.error(`exec error: ${error}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.error(`stderr: ${stderr}`);
});

See the nodejs doc https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

hope it helps

Jerome
  • 294
  • 2
  • 14