/
file-write.js
91 lines (61 loc) · 2.86 KB
/
file-write.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/***********************************************************************************
Abstractor | File writer | MIT License | ©2016 Hexagon <github.com/hexagon>
Writes payload (string/buffer) to a file, encoding and flag are configurable.
Possible flags:
a = append
w = overwrite
----------------------------------------------------------------------------
Options
-----------------+-----------------+----------------------+-----------------
Option | Type | Default | Mandatory
-----------------+-----------------+----------------------+-----------------
path | string | undefined | yes
encoding | string | utf8 | yes
mode | string | 0o666 | yes
flag | string | a | yes
-----------------+-----------------+----------------------+-----------------
I/O
-------------------------------+----------------------+---------------------
Input | Possible triggers | Sets property
-------------------------------+----------------------+---------------------
| success | <none>
payload: <string/buffer> +----------------------+---------------------
| error | error
-------------------------------+----------------------+---------------------
***********************************************************************************/
"use strict";
const
Node = require("../node.js"),
fs = require("fs");
class FileWrite extends Node {
constructor(parameters) {
var defaults = {
encoding: "utf8",
mode: 0o666,
flag: "a"
};
super(parameters, defaults);
}
invoke(msg) {
var
self = this,
// Mandatory options
filePath = this.getConfig("path", msg, true),
// Optinal options, defaults are append, read/write permissions to all and utf8 encoding
encoding = this.getConfig("encoding", msg, true),
mode = this.getConfig("mode", msg, true),
flag = this.getConfig("flag", msg, true);
// File path is mandatory, bail out if not found
if (filePath === undefined)
// getConfig has already emitted an error about this
return;
// Supply file path to next node
msg.path = filePath;
fs.writeFile(filePath, msg.payload, { encoding, mode, flag }, function (err) {
if(err) return self.error( msg, "Error while reading file, " + err );
// No need to replace payload
return self.success(msg, msg.payload);
});
}
}
module.exports = FileWrite;