File node: allow filename to be overridden

This commit is contained in:
Nick O'Leary 2014-02-05 10:25:48 +00:00
parent ae03562f86
commit cef652eef7
2 changed files with 26 additions and 18 deletions

View File

@ -36,7 +36,9 @@
</script>
<script type="text/x-red" data-help-name="file">
<p>Writes the <b>msg.payload</b> to the file specified, e.g. to create a log.</p>
<p>Writes <b>msg.payload</b> to the file specified, e.g. to create a log.</p>
<p>The filename can be overridden by the <code>filename</code> property
of the incoming message.</p>
<p>A newline is added to every message. But this can be turned off if required, for example, to allow binary files to be written.</p>
<p>The default behaviour is to append to the file. This can be changed to overwrite the file each time, for example if you want to output a "static" web page or report.</p>
</script>
@ -46,7 +48,7 @@
category: 'storage-output',
defaults: {
name: {value:""},
filename: {value:"",required:true},
filename: {value:""},
appendNewline: {value:true},
overwriteFile: {value:false}
},

View File

@ -25,22 +25,28 @@ function FileNode(n) {
this.overwriteFile = n.overwriteFile;
var node = this;
this.on("input",function(msg) {
var data = msg.payload;
if (this.appendNewline) {
data += "\n";
}
if (this.overwriteFile) {
fs.writeFile(this.filename, data, function (err) {
if (err) node.warn('Failed to write to file : '+err);
//console.log('Message written to file',this.filename);
});
}
else {
fs.appendFile(this.filename, data, function (err) {
if (err) node.warn('Failed to append to file : '+err);
//console.log('Message appended to file',this.filename);
});
}
var filename = msg.filename || this.filename;
if (filename == "") {
node.warn('No filename specified');
} else {
var data = msg.payload;
if (this.appendNewline) {
data += "\n";
}
if (this.overwriteFile) {
fs.writeFile(filename, data, function (err) {
if (err) node.warn('Failed to write to file : '+err);
//console.log('Message written to file',this.filename);
});
}
else {
fs.appendFile(filename, data, function (err) {
if (err) node.warn('Failed to append to file : '+err);
//console.log('Message appended to file',this.filename);
});
}
}
});
}