M
M
MarEeeeeee2020-10-06 10:17:30
Node.js
MarEeeeeee, 2020-10-06 10:17:30

How to adapt this function to a synchronous version?

I have a function that I need to get all available partitions on a computer. But it works asynchronously, so there is a situation that I cannot receive and send data from it to my web application.

How to fix this problem? Perhaps there are alternative solutions to my problem?

function ListDrives (){
    const list  = spawn('cmd');

    return new Promise((resolve, reject) => {
        list.stdout.on('data', function (data) {            
            const output =  String(data)
            const out = output.split("\r\n").map(e=>e.trim()).filter(e=>e!="")
            if (out[0]==="Name"){
                resolve(out.slice(1))
            }
            // console.log("stdoutput:", out)
        });

        list.stderr.on('data', function (data) {
            // console.log('stderr: ' + data);
        });

        list.on('exit', function (code) {
            console.log('child process exited with code ' + code);
            if (code !== 0){
                reject(code)
            }
        });

        list.stdin.write('wmic logicaldisk get name\n');
        list.stdin.end();
    })
}


серверная часть

<code lang="javascript">
router.post('/drives', (req, res) => {
    console.log("HEEEEEEEEEEEEEE", disks);
    res.send(JSON.stringify(disks));
 })


Часть на вебе
<code lang="javascript">
fetch('/drives', {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin    
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
    
    })
    .then(response => response.json()) 
    .then(json => this.directories = json)
</code>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
monochromer, 2020-10-06
@monochromer

ListDrives().then(data => {
  /* вот здесь и работайте с `data` */
  console.log("HEEEEEEEEEEEEEE", data);
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question