UNPKG

963 BJavaScriptView Raw
1var common = require('./common');
2var fs = require('fs');
3var path = require('path');
4
5common.register('to', _to, {
6 pipeOnly: true,
7 wrapOutput: false,
8});
9
10//@
11//@ ### ShellString.prototype.to(file)
12//@
13//@ Examples:
14//@
15//@ ```javascript
16//@ cat('input.txt').to('output.txt');
17//@ ```
18//@
19//@ Analogous to the redirection operator `>` in Unix, but works with
20//@ `ShellStrings` (such as those returned by `cat`, `grep`, etc.). _Like Unix
21//@ redirections, `to()` will overwrite any existing file!_
22function _to(options, file) {
23 if (!file) common.error('wrong arguments');
24
25 if (!fs.existsSync(path.dirname(file))) {
26 common.error('no such file or directory: ' + path.dirname(file));
27 }
28
29 try {
30 fs.writeFileSync(file, this.stdout || this.toString(), 'utf8');
31 return this;
32 } catch (e) {
33 /* istanbul ignore next */
34 common.error('could not write to file (code ' + e.code + '): ' + file, { continue: true });
35 }
36}
37module.exports = _to;