/** * * @author yutent * @date 2022/07/14 11:06:47 */ const fs = require('fs') const { parse } = require('path') /** * [stat 返回文件/目录的状态信息] * @param {[string]} path [目标路径] */ function stat(path) { try { return fs.statSync(path) } catch (err) { return EMPTY_STAT } } /** * [isdir 判断目标是否为目录] * @param {String} path [目标路径] */ function isdir(path) { try { return stat(path).isDirectory() } catch (err) {} } /** * [mkdir 新建目录] * @param {String} dir [目标路径] * @param {Number} mode [目录权限, node v10.12起支持] */ function mkdir(dir, mode = 0o755) { try { fs.mkdirSync(dir, { recursive: true, mode: mode }) return true } catch (err) {} } // exports.cat = function (file) { try { return fs.readFileSync(file) } catch (e) {} } exports.echo = function (data, file, append) { if (!file) { return data } let updir = parse(file).dir let opt = {} if (!isdir(updir)) { mkdir(updir) } try { if (append) { fs.appendFileSync(file, data, opt) } else { fs.writeFileSync(file, data, opt) } } catch (err) {} } exports.isfile = function (path) { try { return stat(path).isFile() } catch (err) { return false } } exports.writable = function (file) { try { fs.accessSync('/etc/hosts', fs.constants.W_OK) return true } catch (e) { return false } }