Node.js에서 파일에 쓸 때 디렉토리 만들기
나는 Node.js를 땜질하고 약간의 문제를 발견했습니다. 라는 디렉토리에있는 스크립트가 있습니다 data
. 스크립트가 하위 디렉터리 내의 하위 디렉터리에있는 파일에 일부 데이터를 쓰길 원합니다 data
. 그러나 다음과 같은 오류가 발생합니다.
{ [Error: ENOENT, open 'D:\data\tmp\test.txt'] errno: 34, code: 'ENOENT', path: 'D:\\data\\tmp\\test.txt' }
코드는 다음과 같습니다.
var fs = require('fs');
fs.writeFile("tmp/test.txt", "Hey there!", function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
누구든지 Node.js가 파일에 쓰기 위해 종료되지 않는 경우 디렉토리 구조를 만드는 방법을 찾는 데 도움을 줄 수 있습니까?
노드> 10.12.0
fs.mkdir은 이제 { recursive: true }
다음과 같은 옵션을 허용합니다 .
// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
if (err) throw err;
});
또는 약속 :
fs.promises.mkdir('/tmp/a/apple', { recursive: true }).catch(console.error);
노드 <= 10.11.0
mkdirp 또는 fs-extra 와 같은 패키지 로이 문제를 해결할 수 있습니다 . 패키지를 설치하지 않으려면 아래 Tiago Peres França의 답변을 참조하십시오.
추가 패키지를 사용하지 않으려면 파일을 만들기 전에 다음 함수를 호출 할 수 있습니다.
var path = require('path'),
fs = require('fs');
function ensureDirectoryExistence(filePath) {
var dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
}
로 노드-FS-추가 하면 쉽게 할 수있다.
그것을 설치하십시오
npm install --save fs-extra
그런 다음 outputFile
방법을 사용하십시오 . 문서에 따르면 다음과 같습니다.
부모 디렉터리가 존재하지 않으면 생성된다는 점을 제외하면 writeFile과 거의 동일합니다 (즉, 덮어 쓰기).
세 가지 방법으로 사용할 수 있습니다.
콜백 스타일
const fse = require('fs-extra');
fse.outputFile('tmp/test.txt', 'Hey there!', err => {
if(err) {
console.log(err);
} else {
console.log('The file was saved!');
}
})
약속 사용
promises 를 사용하는 경우 다음 코드가 있습니다.
fse.outputFile('tmp/test.txt', 'Hey there!')
.then(() => {
console.log('The file was saved!');
})
.catch(err => {
console.error(err)
});
동기화 버전
동기화 버전을 원하면 다음 코드를 사용하십시오.
fse.outputFileSync('tmp/test.txt', 'Hey there!')
전체 참조를 보려면 outputFile
설명서 및 모든 node-fs-extra 지원 방법을 확인하십시오 .
뻔뻔한 플러그 경고!
You will have to check for each directory in the path structure you want and create it manually if it doesn't exist. All the tools to do so are already there in Node's fs module, but you can do all of that simply with my mkpath module: https://github.com/jrajav/mkpath
Since I cannot comment yet, I'm posting an enhanced answer based on @tiago-peres-frança fantastic solution (thanks!). His code does not make directory in a case where only the last directory is missing in the path, e.g. the input is "C:/test/abc" and "C:/test" already exists. Here is a snippet that works:
function mkdirp(filepath) {
var dirname = path.dirname(filepath);
if (!fs.existsSync(dirname)) {
mkdirp(dirname);
}
fs.mkdirSync(filepath);
}
My advise is: try not to rely on dependencies when you can easily do it with few lines of codes
Here's what you're trying to achieve in 14 lines of code:
fs.isDir = function(dpath) {
try {
return fs.lstatSync(dpath).isDirectory();
} catch(e) {
return false;
}
};
fs.mkdirp = function(dirname) {
dirname = path.normalize(dirname).split(path.sep);
dirname.forEach((sdir,index)=>{
var pathInQuestion = dirname.slice(0,index+1).join(path.sep);
if((!fs.isDir(pathInQuestion)) && pathInQuestion) fs.mkdirSync(pathInQuestion);
});
};
I just published this module because I needed this functionality.
https://www.npmjs.org/package/filendir
It works like a wrapper around Node.js fs methods. So you can use it exactly the same way you would with fs.writeFile
and fs.writeFileSync
(both async and synchronous writes)
참고URL : https://stackoverflow.com/questions/13542667/create-directory-when-writing-to-file-in-node-js
'development' 카테고리의 다른 글
Linq에서 EntityFramework DateTime으로 (0) | 2020.08.15 |
---|---|
JQuery UI Datepicker 필드에 대한 수동 입력을 비활성화하는 방법은 무엇입니까? (0) | 2020.08.15 |
ExpandableListView-자식이없는 그룹에 대한 표시기 숨기기 (0) | 2020.08.15 |
C 빅 엔디안 또는 리틀 엔디안 머신을 결정하는 매크로 정의? (0) | 2020.08.15 |
어떤 요소를 클릭하든 WPF 창을 드래그 가능하게 만듭니다. (0) | 2020.08.15 |