n8n-nodes-base
Version:
Base nodes of n8n
118 lines • 4.59 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.WriteBinaryFile = void 0;
const n8n_workflow_1 = require("n8n-workflow");
const node_fs_1 = require("node:fs");
class WriteBinaryFile {
description = {
hidden: true,
displayName: 'Write Binary File',
name: 'writeBinaryFile',
icon: 'fa:file-export',
group: ['output'],
version: 1,
description: 'Writes a binary file to disk',
defaults: {
name: 'Write Binary File',
color: '#CC2233',
},
inputs: [n8n_workflow_1.NodeConnectionTypes.Main],
outputs: [n8n_workflow_1.NodeConnectionTypes.Main],
properties: [
{
displayName: 'File Name',
name: 'fileName',
type: 'string',
default: '',
required: true,
placeholder: '/data/example.jpg',
description: 'Path to which the file should be written',
},
{
displayName: 'Property Name',
name: 'dataPropertyName',
type: 'string',
default: 'data',
required: true,
description: 'Name of the binary property which contains the data for the file to be written',
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add option',
default: {},
options: [
{
displayName: 'Append',
name: 'append',
type: 'boolean',
default: false,
description: 'Whether to append to an existing file',
},
],
},
],
};
async execute() {
const items = this.getInputData();
const returnData = [];
const length = items.length;
let item;
for (let itemIndex = 0; itemIndex < length; itemIndex++) {
try {
const dataPropertyName = this.getNodeParameter('dataPropertyName', itemIndex);
const fileName = this.getNodeParameter('fileName', itemIndex);
const options = this.getNodeParameter('options', 0, {});
const flag = options.append
? node_fs_1.constants.O_APPEND
: node_fs_1.constants.O_WRONLY | node_fs_1.constants.O_CREAT | node_fs_1.constants.O_TRUNC;
item = items[itemIndex];
const newItem = {
json: {},
pairedItem: {
item: itemIndex,
},
};
Object.assign(newItem.json, item.json);
const binaryData = this.helpers.assertBinaryData(itemIndex, dataPropertyName);
let fileContent;
if (binaryData.id) {
fileContent = await this.helpers.getBinaryStream(binaryData.id);
}
else {
fileContent = Buffer.from(binaryData.data, n8n_workflow_1.BINARY_ENCODING);
}
// Write the file to disk
await this.helpers.writeContentToFile(await this.helpers.resolvePath(fileName), fileContent, flag);
if (item.binary !== undefined) {
// Create a shallow copy of the binary data so that the old
// data references which do not get changed still stay behind
// but the incoming data does not get changed.
newItem.binary = {};
Object.assign(newItem.binary, item.binary);
}
// Add the file name to data
newItem.json.fileName = fileName;
returnData.push(newItem);
}
catch (error) {
if (this.continueOnFail()) {
returnData.push({
json: {
error: error.message,
},
pairedItem: {
item: itemIndex,
},
});
continue;
}
throw error;
}
}
return [returnData];
}
}
exports.WriteBinaryFile = WriteBinaryFile;
//# sourceMappingURL=WriteBinaryFile.node.js.map