Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rm -rf written in Node.js

Tags:

node.js

I'd like to achieve rm -rf or a directory and all of it's contents with the minimum amount of code possible.

I've only found scripts with around 50 lines or more of code, there must be a less than 10 line code snippet for this?

There are two ways of doing this, pure Node.js or using spawn/exec to use the rm -rf command.

rm -rf way:

function spawnCustom(command, options) {
    const array = command.split(' ');
    const first_command = array[0];
    array.shift();
    return new Promise((resolve, reject) => {
        const spawn = require('child_process').spawn;

        const child = spawn(first_command, array, options);
        child.stdout.on('data', function(data) {
            process.stdout.write('stdout: ' + data);
            // Here is where the output goes
        });
        child.stderr.on('data', function(data) {
            process.stdout.write('stderr: ' + data);
            // Here is where the error output goes
            reject(data);
        });
        child.on('close', function(code) {
            process.stdout.write('closing code: ' + code);
            // Here you can get the exit code of the script
            resolve();
        });
    }); 
}

await spawnCustom('rm -rf ~/example_dir');

Node.js way:

const fs = require('fs')
const path = require('path')

let _dirloc = '<path_do_the_directory>'

if (existsSync(_dirloc)) {
    fs.readdir(path, (error, files) => {
        if(!error) {
            for(let file of files) {
                // Delete each file
                fs.unlinkSync(path.join(_dirloc,file))
            }
        }
    })

    // After the done of each file delete,
    // Delete the directory itself
    if(fs.unlinkSync(_dirloc)) {
        console.log('Directory has been deleted!')
    }
}

A lot of code for something simple.. There must be a more simple way?

like image 216
basickarl Avatar asked Jan 01 '23 17:01

basickarl


1 Answers

That would be the rimraf module.

Can be done in 2 lines

 var rimraf = require('rimraf');
 rimraf('/some/directory', () => console.log('done'));
like image 96
Enslev Avatar answered Jan 05 '23 18:01

Enslev