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?
That would be the rimraf module.
Can be done in 2 lines
 var rimraf = require('rimraf');
 rimraf('/some/directory', () => console.log('done'));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With