Programing

Node.js는 폴더를 만들거나 기존 폴더를 사용합니다

lottogame 2020. 5. 25. 08:01
반응형

Node.js는 폴더를 만들거나 기존 폴더를 사용합니다


Node.js의 문서를 이미 읽었으며 무언가를 놓치지 않으면 특정 작업, 특히 매개 변수에 포함 된 내용을 알려주지 않습니다 fs.mkdir(). 문서에서 볼 수 있듯이 그리 많지는 않습니다.

현재이 코드가 있는데 폴더를 만들거나 기존 폴더를 대신 사용하려고합니다.

fs.mkdir(path,function(e){
    if(!e || (e && e.code === 'EEXIST')){
        //do something with contents
    } else {
        //debug
        console.log(e);
    }
});

그러나 이것이 올바른 방법인지 궁금합니다. EEXIST폴더가 이미 존재하는지 알 수있는 올바른 방법으로 코드를 확인하고 있습니까? fs.stat()디렉토리를 만들기 전에 할 수 있다는 것을 알고 있지만 파일 시스템에는 이미 두 가지가 있습니다.

둘째, 오류 객체에 포함 된 내용, 매개 변수의 의미 등에 대한 세부 정보가 포함 된 Node.js에 대한 완전하거나 더 자세한 설명서가 있습니까?


이를 수행하는 좋은 방법은 mkdirp 모듈 을 사용하는 입니다.

$ npm install mkdirp

디렉토리가 필요한 기능을 실행하는 데 사용하십시오. 경로가 생성 된 후 또는 경로가 이미 존재하면 콜백이 호출됩니다. errmkdirp가 디렉토리 경로를 작성하지 못한 경우 오류 가 설정됩니다.

var mkdirp = require('mkdirp');
mkdirp('/tmp/some/path/foo', function(err) { 

    // path exists unless there was an error

});

편집 : 이 답변은 매우 인기가 있기 때문에 최신 사례를 반영하도록 업데이트했습니다.

를 사용하면 try {} catch (err) {}경쟁 조건을 겪지 않고 매우 우아하게 달성 할 수 있습니다.

존재 여부 확인과 디렉토리 작성 사이의 데드 타임을 방지하기 위해 디렉토리를 바로 작성하고 오류가있는 경우 EEXIST(디렉토리가 이미 존재하는 경우) 오류를 무시하려고합니다 .

오류가없는 경우 EEXIST, 그러나, 우리는 우리가 같은 취급 될 수 있기 때문에, 오류가 발생한다고 EPERMEACCES

또한 recursive옵션을 사용하여 다음 mkdir과 같은 동작을 수행 할 수 있습니다 mkdir -p(참고 : 노드> = 10.x에서만 사용 가능)

동기화 버전

const fs = require('fs')

function ensureDirSync (dirpath) {
  try {
    fs.mkdirSync(dirpath, { recursive: true })
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }
}

try {
  ensureDirSync('a/b/c')
  console.log('Directory created')
} catch (err) {
  console.error(err)
}

비동기 버전 (비동기 / 대기, 최신 노드 버전)

const fs = require('fs').promises

async function ensureDir (dirpath) {
  try {
    await fs.mkdir(dirpath, { recursive: true })
  } catch (err) {
    if (err.code !== 'EEXIST') throw err
  }
}

async function main () {
  try {
    await ensureDir('a/b/c')
    console.log('Directory created')
  } catch (err) {
    console.error(err)
  }
}

main()

실험용 fs.promisesAPI 를 사용하지 않으려는 경우 (안정적이며 유지 하려는 경우 에도) 다음을 수행 할 수 있습니다 fs.mkdir.

await new Promise((resolve, reject) => {
  fs.mkdir(dirpath, { recursive: true }, err => err ? reject(err) : resolve())
})

비동기 버전 (약속, 레거시 노드 버전)

참고 : recursive10.x 이전 버전의 노드 에는 새로운 옵션 이 없으므로 경로의 모든 부분을 만들어야합니다.

const fs = require('fs')

function ensureDir (dirpath) {
  return fs.mkdir(dirpath, function (err) {
    if (err.code === 'EEXIST') {
      return Promise.resolve()
    } else {
      return Promise.reject(err)
    }
  })
}

Promise.resolve()
  .then(function () { ensureDir('a') })
  .then(function () { ensureDir('a/b') })
  .then(function () { ensureDir('a/b/c') })
  .then(function () { console.log('Directory created') })
  .catch(function () { console.error(err) })

빠르고 더러운 하나의 라이너를 원한다면 다음을 사용하십시오.

fs.existsSync("directory") || fs.mkdirSync("directory");

node.js 문서는 fs.mkdir기본적으로에 대한 Linux 매뉴얼 페이지를 참조하십시오 mkdir(2). 즉 그 나타내는 EEXIST경로가 존재하지만이 경로를 이동하는 경우 어색한 코너 케이스를 생성하는 디렉토리가 아닌 경우에도 표시됩니다.

fs.stat경로가 존재하는지 여부와 단일 호출의 디렉토리인지 알려주는 호출 더 나을 수 있습니다 . 디렉토리가 이미 존재하는 일반적인 경우 (단일 가정)의 경우 단일 파일 시스템 적중입니다.

fs모듈 메소드는 네이티브 C API를 둘러싼 얇은 래퍼이므로 자세한 내용은 node.js 문서에서 참조 된 매뉴얼 페이지를 확인해야합니다.


이것을 사용할 수 있습니다 :

if(!fs.existsSync("directory")){
    fs.mkdirSync("directory", 0766, function(err){
        if(err){
            console.log(err);
            // echo the result back
            response.send("ERROR! Can't make the directory! \n");
        }
    });
}

모듈이없는 솔루션을 제안합니다 (누적 모듈은 특히 몇 줄로 작성할 수있는 작은 기능의 유지 관리를 위해 권장되지 않습니다 ...) :

마지막 업데이트 :

v10.12.0에서 NodeJS 구현 재귀 옵션 :

// Create recursive folder
fs.mkdir('my/new/folder/create', { recursive: true }, (err) => { if (err) throw err; });

업데이트 :

// Get modules node
const fs   = require('fs');
const path = require('path');

// Create 
function mkdirpath(dirPath)
{
    if(!fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK))
    {
        try
        {
            fs.mkdirSync(dirPath);
        }
        catch(e)
        {
            mkdirpath(path.dirname(dirPath));
            mkdirpath(dirPath);
        }
    }
}

// Create folder path
mkdirpath('my/new/folder/create');

디렉토리를 만들 때 사용하는 ES6 코드는 다음과 같습니다 (없는 경우).

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

function createDirectory(directoryPath) {
  const directory = path.normalize(directoryPath);

  return new Promise((resolve, reject) => {
    fs.stat(directory, (error) => {
      if (error) {
        if (error.code === 'ENOENT') {
          fs.mkdir(directory, (error) => {
            if (error) {
              reject(error);
            } else {
              resolve(directory);
            }
          });
        } else {
          reject(error);
        }
      } else {
        resolve(directory);
      }
    });
  });
}

const directoryPath = `${__dirname}/test`;

createDirectory(directoryPath).then((path) => {
  console.log(`Successfully created directory: '${path}'`);
}).catch((error) => {
  console.log(`Problem creating directory: ${error.message}`)
});

노트 :

  • 의 초기에는 createDirectory기능, I (예 :이 켜집니다 운영 체제의 경로 구분자 유형이 지속적으로 사용됩니다 보장의 경로를 정상화 C:\directory/test으로 C:\directory\test(윈도우에있는 경우)
  • fs.exists되어 사용되지 않는 내가 사용하는 이유, 그건 fs.stat디렉토리가 이미 존재하는지 확인
  • 디렉토리가 존재하지 않는 경우, 에러 코드가 될 것입니다 ENOENT( E rror NO ENT 공예)
  • The directory itself will be created using fs.mkdir
  • I prefer the asynchronous function fs.mkdir over it's blocking counterpart fs.mkdirSync and because of the wrapping Promise it will be guaranteed that the path of the directory will only be returned after the directory has been successfully created

You'd better not to count the filesystem hits while you code in Javascript, in my opinion. However, (1) stat & mkdir and (2) mkdir and check(or discard) the error code, both ways are right ways to do what you want.


You can also use fs-extra, which provide a lot frequently used file operations.

Sample Code:

var fs = require('fs-extra')

fs.mkdirs('/tmp/some/long/path/that/prob/doesnt/exist', function (err) {
  if (err) return console.error(err)
  console.log("success!")
})

fs.mkdirsSync('/tmp/another/path')

docs here: https://github.com/jprichardson/node-fs-extra#mkdirsdir-callback


create dynamic name directory for each user... use this code

***suppose email contain user mail address***

var filessystem = require('fs');
var dir = './public/uploads/'+email;

if (!filessystem.existsSync(dir)){
  filessystem.mkdirSync(dir);

}else
{
    console.log("Directory already exist");
}

Raugaral's answer but with -p functionality. Ugly, but it works:

function mkdirp(dir) {
    let dirs = dir.split(/\\/).filter(asdf => !asdf.match(/^\s*$/))
    let fullpath = ''

    // Production directory will begin \\, test is on my local drive.
    if (dirs[0].match(/C:/i)) {
        fullpath = dirs[0] + '\\'
    }
    else {
        fullpath = '\\\\' + dirs[0] + '\\'
    }

    // Start from root directory + 1, build out one level at a time.
    dirs.slice(1).map(asdf => {
        fullpath += asdf + '\\'
        if (!fs.existsSync(fullpath)) {
            fs.mkdirSync(fullpath)
        }
    })
}//mkdirp

Just as a newer alternative to Teemu Ikonen's answer, which is very simple and easily readable, is to use the ensureDir method of the fs-extra package.

It can not only be used as a blatant replacement for the built in fs module, but also has a lot of other functionalities in addition to the functionalities of the fs package.

The ensureDir method, as the name suggests, ensures that the directory exists. If the directory structure does not exist, it is created. Like mkdir -p. Not just the end folder, instead the entire path is created if not existing already.

the one provided above is the async version of it. It also has a synchronous method to perform this in the form of the ensureDirSync method.


You can do all of this with the File System module.

const
  fs = require('fs'),
  dirPath = `path/to/dir`

// Check if directory exists.
fs.access(dirPath, fs.constants.F_OK, (err)=>{
  if (err){
    // Create directory if directory does not exist.
    fs.mkdir(dirPath, {recursive:true}, (err)=>{
      if (err) console.log(`Error creating directory: ${err}`)
      else console.log('Directory created successfully.')
    })
  }
  // Directory now exists.
})

You really don't even need to check if the directory exists. The following code also guarantees that the directory either already exists or is created.

const
  fs = require('fs'),
  dirPath = `path/to/dir`

// Create directory if directory does not exist.
fs.mkdir(dirPath, {recursive:true}, (err)=>{
  if (err) console.log(`Error creating directory: ${err}`)
  // Directory now exists.
})

참고URL : https://stackoverflow.com/questions/13696148/node-js-create-folder-or-use-existing

반응형