UNPKG

runok

Version:

NPM scripts on steroids! Replace your scripts with pure JS

63 lines (62 loc) 1.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const task_1 = require("../task"); const result_1 = require("../result"); const fs = require('fs'); const path = require('path'); /** * Writes a data to file. * * Takes file name as first argument and config function as second. * * ```js * writeToFile('blog-post.md', cfg => { * cfg.line('---'); * cfg.line('title: My blogpost'); * cfg.line('---'); * cfg.line(); * cfg.textFromFile('blog-post.txt'); * cfg.text += '// copyright by me'; * }); * ``` * * A second argument is a config function that passes in an object for text manipulation. * * ### Config API * * * `cfg.text` - string to be written to file * * `cfg.textFromFile(file)` - loads a file and append its context to text * * `cfg.line(text)` - appends a string to a text with "\n" after * * `cfg.append(text)` - appends a string to a text */ function writeToFile(file, configFn) { file = path.join(process.cwd(), file); const config = new WriteToFileConfig(file); config.apply(configFn); const result = result_1.Result.start(config.TASK, config.file); try { fs.writeFileSync(config.file, config.text); } catch (error) { return result.fail(error); } return result.success({ text: config.text }); } exports.default = writeToFile; class WriteToFileConfig extends task_1.TaskConfig { constructor(file) { super(); this.TASK = 'writeToFile'; this.file = file; this.text = ''; } textFromFile(file) { this.text += fs.readFileSync(path.join(process.cwd(), file)); } line(line) { this.text += `${line}\n`; } append(text) { this.text += text; } }