2 * Copyright 2013, 2014 IBM Corp.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 module.exports = function(RED) {
19 var fs = require("fs");
21 function FileNode(n) {
22 RED.nodes.createNode(this,n);
23 this.filename = n.filename || "";
24 this.appendNewline = n.appendNewline;
25 this.overwriteFile = n.overwriteFile;
27 this.on("input",function(msg) {
28 var filename = msg.filename || this.filename;
29 if (filename === "") {
30 node.warn('No filename specified');
31 } else if (msg.hasOwnProperty('delete')) {
32 fs.unlink(filename, function (err) {
33 if (err) { node.warn('Failed to delete file : '+err); }
34 //console.log('Deleted file",filename);
36 } else if (typeof msg.payload != "undefined") {
37 var data = msg.payload;
38 if (typeof data === "object") {
39 if (!Buffer.isBuffer(data)) {
40 data = JSON.stringify(data);
43 if (typeof data === "boolean") { data = data.toString(); }
44 if ((this.appendNewline)&&(!Buffer.isBuffer(data))) { data += "\n"; }
45 if (this.overwriteFile) {
46 // using "binary" not {encoding:"binary"} to be 0.8 compatible for a while
47 fs.writeFile(filename, data, "binary", function (err) {
48 if (err) { node.warn('Failed to write to file : '+err); }
49 //console.log('Message written to file',filename);
53 // using "binary" not {encoding:"binary"} to be 0.8 compatible for a while
54 fs.appendFile(filename, data, "binary", function (err) {
55 if (err) { node.warn('Failed to append to file : '+err); }
56 //console.log('Message appended to file',filename);
62 RED.nodes.registerType("file",FileNode);
64 function FileInNode(n) {
65 RED.nodes.createNode(this,n);
67 this.filename = n.filename || "";
68 this.format = n.format;
72 options['encoding'] = this.format;
74 this.on("input",function(msg) {
75 var filename = msg.filename || this.filename;
76 if (filename === "") {
77 node.warn('No filename specified');
79 fs.readFile(filename,options,function(err,data) {
84 msg.filename = filename;
92 RED.nodes.registerType("file in",FileInNode);