ฉันกำลังซ่อมแซม 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 สร้างโครงสร้างไดเรกทอรีถ้ามันไม่ออกจากการเขียนไปยังไฟล์?
fs.promises.mkdir(path.dirname("tmp/test.txt"), {recursive: true}).then(x => fs.promises.writeFile("tmp/test.txt", "Hey there!"))