Search code examples
javascriptnode.jsfilesystemsfs

creating a directory with subdirectories and files in node


i want to run a script that will create a directory and within a file and subdirectory, something like this

main-folder 
    > sub-folder
    > file

so far i haven't had any luck, my thought is trying to writeFile within the mkDir function

const fileGenerator = (fileName, fileContent) => {
    fs.writeFile(fileName, fileContent, (err) => {
        if (err) throw err;
        console.log('The file has been saved!');
    });
}

fs.mkdir('main-folder', err => {
    if (err) {
        console.log(err);
    } else {
        fileGenerator('index.html', 'hello');
        console.log('Directory Created');
        fs.mkdir('sub-folder', err => {
        if (err) {
            console.log(err);
        } else {
            console.log('Directory Created');
        }
    })
    }
})

Solution

  • The code is 'working as inteded'. The place where're you creating your subfolder and file is just the callback. The mkdir function from the Node Filesystem still needs the full path. It doesn't know that its under "main-folder".

    See the edited code:

    const fs = require('fs');
    const fileGenerator = (fileName, fileContent) => {
        fs.writeFile(fileName, fileContent, (err) => {
            if (err) throw err;
            console.log('The file has been saved!');
        });
    }
    
    fs.mkdir('main-folder', err => {
        if (err) {
            console.log(err);
        } else {
            fileGenerator('main-folder/index.html', 'hello');
            console.log('Directory Created');
            fs.mkdir('main-folder/sub-folder', err => {
            if (err) {
                console.log(err);
            } else {
                console.log('Directory Created');
            }
        })
        }
    })
    

    Your code created the main-folder, sub-folder and index.html, just all relative to js file.