// 异步
const fs = require('fs');
fs.mkdir('my-directory', { recursive: true }, (err) => {
if (err) {
return console.error('Error creating directory:', err);
}
console.log('Directory created successfully!');
});
// 同步
const fs = require('fs');
try {
fs.mkdirSync('my-directory', { recursive: true });
console.log('Directory created successfully!');
} catch (err) {
console.error('Error creating directory:', err);
}
// 写入文件的最终方案
const fs = require('fs');
const path = require('path');
// 要写入文件的路径拼接系统路径/或者\
const filePath = path.join('path', 'to', 'directory', 'file.txt');
// 获取文件所在的目录路径
const dir = path.dirname(filePath);
// 递归创建目录(如果不存在)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
// 写入文件
fs.writeFileSync(filePath, '这是文件的内容', 'utf8');
console.log('文件写入成功');
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)