Create folder/directory with Node.JS

Asked

Viewed 3,164 times

3

There is the module "Fs", which is used to create files:

const fs = require("fs");
fs.writeFile(`./teste.txt`, "conteúdo",
        function (erro) {
            if (erro) {
                throw erro;
            }
            console.log("Arquivo salvo com sucesso!");
        });

I wonder if there is any way I can create a directory in a similar way.

1 answer

6


There are some methods within the fs that allow the creation of directories, one of them is the mkdirSync, example:

const fs = require('fs');
const dir = "C:/Temp/Xisto";

//Verifica se não existe
if (!fs.existsSync(dir)){
    //Efetua a criação do diretório
    fs.mkdirSync(dir);
}

As its name already says, it is a synchronous method.

See online: https://repl.it/repls/UnrulyOrangeBit


There is also the mkdir, the difference being asynchronous:

const fs = require('fs');
const dir = "C:/Temp/Xisto";

//Verifica se não existe
if (!fs.existsSync(dir)){
    //Efetua a criação do diretório
    fs.mkdir(dir, (err) => {
        if (err) {
            console.log("Deu ruim...");
            return
        }

        console.log("Diretório criado! =)")
    });
}

See online: https://repl.it/repls/PoliteDownrightTrial


Reference: https://nodejs.org/api/fs.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.