UNPKG

@viewdo/dxp-story-cli

Version:
58 lines (46 loc) 1.5 kB
const fs = require('fs') const mkdirp = require('mkdirp') const path = require('path') const {requireValue} = require('./utils') const console = require('./console-service') module.exports = class FileService { // properties ------------------------------- constructor(root = requireValue('root')) { Object.assign(this, { root: root || process.cwd() }) } // File API ------------------------------- exists(file_path) { let full_path = this._getFullPath(file_path) console.debug('Checking file path: ' + full_path) return fs.existsSync(full_path) } read(file_path) { let full_path = this._getFullPath(file_path) console.debug('Reading file path: ' + full_path) if(this.exists(file_path)) return fs.readFileSync(full_path, 'utf8') } ensure(file_path) { if(!this.exists(file_path)) this.write(file_path) } write(file_path, content = '') { let full_path = this._getFullPath(file_path) console.debug('Writing file path: ' + full_path) let directory = path.dirname(full_path) console.debug('-> directory: ' + directory) mkdirp.sync(directory, {}) return fs.writeFileSync(full_path, content, 'utf8') } delete(file_path) { let full_path = this._getFullPath(file_path) console.debug('Deleting file path: ' + full_path) if(this.exists(file_path)) return fs.unlinkSync(full_path) } _getFullPath(file_path) { return path.join(this.root, path.normalize(file_path)) } }