UNPKG

2.09 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6
7var _fs = require('fs');
8
9var _fs2 = _interopRequireDefault(_fs);
10
11function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
13// Taken from http://stackoverflow.com/questions/3430939/node-js-readsync-from-stdin/16048083#16048083
14function readStdin() {
15 var BUFSIZE = 256;
16 var buf = 'alloc' in Buffer ? Buffer.alloc(BUFSIZE) : new Buffer(BUFSIZE);
17 var bytesRead = void 0;
18 var out = '';
19
20 do {
21 try {
22 bytesRead = _fs2.default.readSync(process.stdin.fd, buf, 0, BUFSIZE);
23 } catch (e) {
24 if (e.code === 'EAGAIN') {
25 // 'resource temporarily unavailable'
26 // Happens on OS X 10.8.3 (not Windows 7!), if there's no
27 // stdin input - typically when invoking a script without any
28 // input (for interactive stdin input).
29 // If you were to just continue, you'd create a tight loop.
30 throw e;
31 } else if (e.code === 'EOF') {
32 // Happens on Windows 7, but not OS X 10.8.3:
33 // simply signals the end of *piped* stdin input.
34 break;
35 }
36 throw e; // unexpected exception
37 }
38 // Process the chunk read.
39 out += buf.toString('utf8', 0, bytesRead);
40 } while (bytesRead !== 0); // Loop as long as stdin input is available.
41
42 return out;
43}
44
45/**
46 * Input/output helpers.
47 */
48exports.default = {
49 /**
50 * Returns the contents of an entire file.
51 * When no filename given, reads from STDIN.
52 * @param {String} filename
53 * @return {String}
54 */
55 read: function read(filename) {
56 if (filename) {
57 return _fs2.default.readFileSync(filename).toString();
58 } else {
59 return readStdin();
60 }
61 },
62
63
64 /**
65 * Writes the data to file.
66 * When no filename given, writes to STDIN.
67 * @param {String} filename
68 * @param {String} data
69 */
70 write: function write(filename, data) {
71 if (filename) {
72 _fs2.default.writeFileSync(filename, data);
73 } else {
74 process.stdout.write(data);
75 }
76 }
77};
78module.exports = exports['default'];
\No newline at end of file