From bb60a97f76732ad3d663edff1f810d4c6fda3bb5 Mon Sep 17 00:00:00 2001 From: Aleksandr Statciuk Date: Thu, 10 Feb 2022 21:22:23 +0300 Subject: [PATCH] Create file.js --- scripts/core/file.js | 68 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 scripts/core/file.js diff --git a/scripts/core/file.js b/scripts/core/file.js new file mode 100644 index 0000000..ecb4a04 --- /dev/null +++ b/scripts/core/file.js @@ -0,0 +1,68 @@ +const path = require('path') +const glob = require('glob') +const fs = require('mz/fs') + +const file = {} + +file.list = function (pattern) { + return new Promise(resolve => { + glob(pattern, function (err, files) { + resolve(files) + }) + }) +} + +file.getFilename = function (filepath) { + return path.parse(filepath).name +} + +file.createDir = async function (dir) { + if (await file.exists(dir)) return + + return fs.mkdir(dir, { recursive: true }).catch(console.error) +} + +file.exists = function (filepath) { + return fs.exists(path.resolve(filepath)) +} + +file.read = function (filepath) { + return fs.readFile(path.resolve(filepath), { encoding: 'utf8' }).catch(console.error) +} + +file.append = function (filepath, data) { + return fs.appendFile(path.resolve(filepath), data).catch(console.error) +} + +file.create = function (filepath, data = '') { + filepath = path.resolve(filepath) + const dir = path.dirname(filepath) + + return file + .createDir(dir) + .then(() => file.write(filepath, data)) + .catch(console.error) +} + +file.write = function (filepath, data = '') { + return fs.writeFile(path.resolve(filepath), data, { encoding: 'utf8' }).catch(console.error) +} + +file.clear = async function (filepath) { + if (await file.exists(filepath)) return file.write(filepath, '') + return true +} + +file.resolve = function (filepath) { + return path.resolve(filepath) +} + +file.dirname = function (filepath) { + return path.dirname(filepath) +} + +file.basename = function (filepath) { + return path.basename(filepath) +} + +module.exports = file