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.fs.dir가 수신하게 되었습니다.{ 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);
메모들,
많은 경우,
fs.mkdirSync
보다는fs.mkdir
후행 슬래시를 포함해도 무해 / 효과가 없습니다.
mkdirSync/mkdir 디렉토리가 이미 존재하는 경우, 존재 여부를 확인할 필요가 없습니다.
노드 <= 10.11.0
mkdirp 또는 fs-extra와 같은 패키지로 해결할 수 있습니다.패키지를 인스톨 하고 싶지 않은 경우는, 아래의 Tiago Peres Franca의 회답을 참조해 주세요.
추가 패키지를 사용하지 않으려면 파일을 만들기 전에 다음 함수를 호출할 수 있습니다.
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);
}
node-fs-extra를 사용하면 쉽게 할 수 있습니다.
인스톨
npm install --save fs-extra
그 후 를 사용합니다.outputFile
방법.문서에는 다음과 같이 기재되어 있습니다.
와 거의 같다
writeFile
(즉, 덮어쓰기) 상위 디렉토리가 존재하지 않는 경우 작성됩니다.
네 가지 방법으로 사용할 수 있습니다.
비동기/대기
const fse = require('fs-extra');
await fse.outputFile('tmp/test.txt', 'Hey there!');
약속의 사용
약속을 사용하는 경우 코드는 다음과 같습니다.
const fse = require('fs-extra');
fse.outputFile('tmp/test.txt', 'Hey there!')
.then(() => {
console.log('The file has been saved!');
})
.catch(err => {
console.error(err)
});
콜백 스타일
const fse = require('fs-extra');
fse.outputFile('tmp/test.txt', 'Hey there!', err => {
if(err) {
console.log(err);
} else {
console.log('The file has been saved!');
}
})
버전 동기화
동기화 버전을 사용하려면 다음 코드를 사용하십시오.
const fse = require('fs-extra')
fse.outputFileSync('tmp/test.txt', 'Hey there!')
자세한 내용은 매뉴얼 및 지원되는 모든 node-fs-extra 메서드를 참조하십시오.
뻔뻔한 플러그 경보!
경로 구조의 각 디렉토리를 확인하고 존재하지 않는 경우 수동으로 작성해야 합니다.이를 위한 모든 툴은 이미 노드의 fs 모듈에 있지만 mkpath 모듈(https://github.com/jrajav/mkpath)을 사용하면 이 모든 것을 간단히 수행할 수 있습니다.
아직 코멘트를 할 수 없기 때문에, @tiago-peres-fransa의 훌륭한 솔루션에 근거해 강화된 답변을 투고합니다(감사합니다).입력이 "C:/test/abc"이고 "C:/test"가 이미 존재하는 경우와 같이 경로에 마지막 디렉토리만 없는 경우에는 이 코드가 디렉토리를 만들지 않습니다.여기 동작하는 스니펫이 있습니다.
function mkdirp(filepath) {
var dirname = path.dirname(filepath);
if (!fs.existsSync(dirname)) {
mkdirp(dirname);
}
fs.mkdirSync(filepath);
}
「」가 붙어 .async await
로로사!!!!!!!!!!!!
const fs = require('fs/promises');
const path = require('path');
async function isExists(path) {
try {
await fs.access(path);
return true;
} catch {
return false;
}
};
async function writeFile(filePath, data) {
try {
const dirname = path.dirname(filePath);
const exist = await isExists(dirname);
if (!exist) {
await fs.mkdir(dirname, {recursive: true});
}
await fs.writeFile(filePath, data, 'utf8');
} catch (err) {
throw new Error(err);
}
}
예:
(async () {
const data = 'Hello, World!';
await writeFile('dist/posts/hello-world.html', data);
})();
몇 줄의 코드로 간단하게 할 수 있는 경우는, 의존성에 의존하지 말아 주세요.
14줄의 코드로 달성하려고 하는 것은 다음과 같습니다.
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);
});
};
이 기능이 필요했기 때문에 이 모듈을 공개했습니다.
https://www.npmjs.org/package/filendir
Node.js fs는 Node.js fs입니다. 이렇게 할 수 요.fs.writeFile
★★★★★★★★★★★★★★★★★」fs.writeFileSync
및 모두) ('비동기 쓰기
언급URL : https://stackoverflow.com/questions/13542667/create-directory-when-writing-to-file-in-node-js
'programing' 카테고리의 다른 글
Chrome 송신 요청 오류:TypeError: 원형 구조를 JSON으로 변환하는 중 (0) | 2023.02.04 |
---|---|
IOUtils.toString(InputStream)에 상당하는 Guava (0) | 2023.02.04 |
URL에서 YouTube 비디오 ID를 얻으려면 어떻게 해야 하나요? (0) | 2023.02.04 |
window.onload vs $(최소)입니다.ready() (0) | 2023.01.25 |
.syslog 프리펜드 .after() 및 .before() (0) | 2023.01.25 |