Program Tip

상위 폴더가없는 경우 파일을 작성하는 방법은 무엇입니까?

programtip 2020. 10. 23. 08:19
반응형

상위 폴더가없는 경우 파일을 작성하는 방법은 무엇입니까?


다음 경로에 파일을 써야합니다.

 fs.writeFile('/folder1/folder2/file.txt', 'content', function () {

 });

그러나 '/folder1/folder2'경로가 존재하지 않을 수 있습니다. 그래서 다음과 같은 오류가 발생합니다.

 message=ENOENT, open /folder1/folder2/file.txt

해당 경로에 콘텐츠를 어떻게 쓸 수 있습니까?


first 와 함께 mkdirp사용하십시오 path.dirname.

var mkdirp = require('mkdirp');
var fs = require('fs');
var getDirName = require('path').dirname;

function writeFile(path, contents, cb) {
  mkdirp(getDirName(path), function (err) {
    if (err) return cb(err);

    fs.writeFile(path, contents, cb);
  });
}

전체 경로가 이미 존재 mkdirp하는 경우 noop입니다. 그렇지 않으면 누락 된 모든 디렉토리가 생성됩니다.

이 모듈은 https://npmjs.org/package/writefile 원하는 것을 수행합니다 . "writefile mkdirp"를 검색 할 때 확인했습니다. 이 모듈은 콜백을받는 대신 promise를 반환하므로 먼저 promise에 대한 소개를 읽어야합니다. 실제로 당신을 복잡하게 만들 수 있습니다.

내가 준 기능은 어쨌든 작동합니다.


가장 쉬운 방법 fs-extra 모듈 outputFile () 메서드 를 사용하는 것 입니다.

부모 디렉터리가 존재하지 않으면 생성된다는 점을 제외하면 writeFile과 거의 동일합니다 (즉, 덮어 씁니다). 옵션은 fs.writeFile ()에 전달하는 것입니다.

예:

var fs = require('fs-extra');
var file = '/tmp/this/path/does/not/exist/file.txt'

fs.outputFile(file, 'hello!', function (err) {
    console.log(err); // => null

    fs.readFile(file, 'utf8', function (err, data) {
        console.log(data); // => hello!
    });
});

그것은 또한 요즘 상자에서 즉시 지원을 약속합니다!.


아마도 가장 간단하게 fs-path npm 모듈을 사용할 수 있습니다 .

코드는 다음과 같습니다.

var fsPath = require('fs-path');

fsPath.writeFile('/folder1/folder2/file.txt', 'content', function(err){
  if(err) {
    throw err;
  } else {
    console.log('wrote a file like DaVinci drew machines');
  }
});

편집하다

NodeJS 버전 (10)은 기본 지원을 모두 추가했습니다 mkdirmkdirSync함께 반복적으로 부모의 감독을 생성하는 recursive: true다음과 같은 옵션 :

fs.mkdirSync(targetDir, { recursive: true });

원하는 경우 다음과 같이 fs Promises API쓸 수 있습니다.

fs.promises.mkdir(targetDir, { recursive: true });

원래 답변

부모 디렉터리가 없으면 재귀 적으로 만듭니다! ( 제로 의존성 )

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

function mkDirByPathSync(targetDir, { isRelativeToScript = false } = {}) {
  const sep = path.sep;
  const initDir = path.isAbsolute(targetDir) ? sep : '';
  const baseDir = isRelativeToScript ? __dirname : '.';

  return targetDir.split(sep).reduce((parentDir, childDir) => {
    const curDir = path.resolve(baseDir, parentDir, childDir);
    try {
      fs.mkdirSync(curDir);
    } catch (err) {
      if (err.code === 'EEXIST') { // curDir already exists!
        return curDir;
      }

      // To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows.
      if (err.code === 'ENOENT') { // Throw the original parentDir error on curDir `ENOENT` failure.
        throw new Error(`EACCES: permission denied, mkdir '${parentDir}'`);
      }

      const caughtErr = ['EACCES', 'EPERM', 'EISDIR'].indexOf(err.code) > -1;
      if (!caughtErr || caughtErr && curDir === path.resolve(targetDir)) {
        throw err; // Throw if it's just the last created dir.
      }
    }

    return curDir;
  }, initDir);
}

용법

// Default, make directories relative to current working directory.
mkDirByPathSync('path/to/dir');

// Make directories relative to the current script.
mkDirByPathSync('path/to/dir', {isRelativeToScript: true});

// Make directories with an absolute path.
mkDirByPathSync('/path/to/dir');

데모

시도 해봐!

설명

  • [업데이트] 등이 솔루션 핸들의 플랫폼 별 오류 EISDIRMac과에 대한 EPERMEACCESWindows 용.
  • 이 솔루션은 상대 경로 절대 경로를 모두 처리 합니다.
  • 상대 경로의 경우 현재 작업 디렉토리에 대상 디렉토리가 생성 (해결)됩니다. 현재 스크립트 디렉토리를 기준으로 문제를 해결하려면 {isRelativeToScript: true}.
  • 사용 path.seppath.resolve()뿐만 아니라, /크로스 플랫폼 문제를 방지하기 위해 연결.
  • Using fs.mkdirSync and handling the error with try/catch if thrown to handle race conditions: another process may add the file between the calls to fs.existsSync() and fs.mkdirSync() and causes an exception.
    • The other way to achieve that could be checking if a file exists then creating it, I.e, if (!fs.existsSync(curDir) fs.mkdirSync(curDir);. But this is an anti-pattern that leaves the code vulnerable to race conditions.
  • Requires Node v6 and newer to support destructuring. (If you have problems implementing this solution with old Node versions, just leave me a comment)

You can use

fs.stat('/folder1/folder2', function(err, stats){ ... });

stats is a fs.Stats type of object, you may check stats.isDirectory(). Depending on the examination of err and stats you can do something, fs.mkdir( ... ) or throw an error.

Reference

Update: Fixed the commas in the code.


Here's my custom function to recursively create directories (with no external dependencies):

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

var myMkdirSync = function(dir){
    if (fs.existsSync(dir)){
        return
    }

    try{
        fs.mkdirSync(dir)
    }catch(err){
        if(err.code == 'ENOENT'){
            myMkdirSync(path.dirname(dir)) //create parent dir
            myMkdirSync(dir) //create dir
        }
    }
}

myMkdirSync(path.dirname(filePath));
var file = fs.createWriteStream(filePath);

Here is my function which works in Node 10.12.0. Hope this will help.

const fs = require('fs');
function(dir,filename,content){
        fs.promises.mkdir(dir, { recursive: true }).catch(error => { console.error('caught exception : ', error.message); });
        fs.writeFile(dir+filename, content, function (err) {
            if (err) throw err;
            console.info('file saved!');
        });
    }

Here's part of Myrne Stol's answer broken out as a separate answer:

This module does what you want: https://npmjs.org/package/writefile . Got it when googling for "writefile mkdirp". This module returns a promise instead of taking a callback, so be sure to read some introduction to promises first. It might actually complicate things for you.

참고URL : https://stackoverflow.com/questions/16316330/how-to-write-file-if-parent-folder-doesnt-exist

반응형