nodejs判断文件、文件夹是否存在,不存在则创建

方法解释

  • ensureFileExistence(filePath)
    • 接受一个文件路径作为参数。
    • 使用 path.dirname(filePath) 获取文件目录路径。
    • 使用 fs.existsSyncfs.mkdirSync 确保目录存在。
    • 使用 fs.existsSyncfs.writeFileSync 确保文件存在。

使用示例

  • 可以调用 ensureFileExistence 方法,并传递你要检查和创建的文件路径。

以下是将文件和目录检查与创建操作封装到一个方法中的示例:

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

function ensureFileExistence(filePath) {
    // 获取文件目录路径
    const dirPath = path.dirname(filePath);

    // 确保目录存在
    if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, { recursive: true });
        console.log(`Directory ${dirPath} created.`);
    } else {
        console.log(`Directory ${dirPath} already exists.`);
    }

    // 确保文件存在
    if (!fs.existsSync(filePath)) {
        fs.writeFileSync(filePath, '', 'utf8'); // 创建空文件
        console.log(`File ${filePath} created.`);
    } else {
        console.log(`File ${filePath} already exists.`);
    }
}

// 使用示例
// 文件路径
// const filePath = path.join(__dirname, './i18n/langs/language.yaml');
const filePath = path.resolve('./i18n/langs/language.yaml');
ensureFileExistence(filePath);

https://blog.csdn.net/weixin_44308055/article/details/106043818

posted @ 2024-05-31 16:03  槑孒  阅读(581)  评论(0编辑  收藏  举报