Skip to main content

Appending to Files

This tutorial shows how to add data to existing files on an OPC UA server without overwriting them.

When to Use Append Mode

Use WriteAppend mode when you need to:

  • Add log entries to existing log files
  • Continuously record sensor data
  • Build cumulative reports
  • Preserve existing file content while adding new data

Quick Start

Basic Append Flow

[ Inject ] → [ Function ] → [ OPC UA File Operation ] → [ Debug ]

Function Node:

msg.payload = "New log entry: " + new Date().toISOString() + "\n";
return msg;

OPC UA File Operation Configuration:

  • Mode: WriteAppend
  • NodeId: ns=1;s=LogFile
  • Encoding: utf8

Each time you trigger the inject, a new line is added to the end of the file.

Common Use Cases

Logging Events

// Function node
const timestamp = new Date().toISOString();
const level = msg.level || "INFO";
msg.payload = `[${timestamp}] ${level}: ${msg.payload}\n`;
return msg;

Result in file:

[2025-11-24T10:00:00.000Z] INFO: System started
[2025-11-24T10:15:23.000Z] WARN: High memory usage
[2025-11-24T10:30:45.000Z] ERROR: Connection failed

Recording Sensor Data

// Function node
const data = {
timestamp: new Date().toISOString(),
temperature: msg.payload.temp,
humidity: msg.payload.humidity
};
msg.payload = JSON.stringify(data) + "\n";
return msg;

Result in file (JSONL format):

{"timestamp":"2025-11-24T10:00:00.000Z","temperature":22.5,"humidity":55}
{"timestamp":"2025-11-24T10:01:00.000Z","temperature":22.7,"humidity":54}
{"timestamp":"2025-11-24T10:02:00.000Z","temperature":22.6,"humidity":55}

Appending to CSV Files

// Function node - assumes CSV file already has headers
const row = `${msg.id},${msg.name},${msg.value}`;
msg.payload = row + "\n";
return msg;

Result in file:

ID,Name,Value
1,Sensor1,42.5
2,Sensor2,38.2
3,Sensor3,45.7

Important Notes

  • Always add newline characters (\n) at the end of your payload to keep entries on separate lines
  • File must exist - create it first with Write mode if needed
  • No size limit - the node handles large files automatically
  • Thread-safe - multiple appends are handled sequentially by the server

Append vs Write

ModeEffectUse Case
WriteReplaces entire fileReports, configs, complete data exports
WriteAppendAdds to end of fileLogs, continuous monitoring, incremental data

Error Handling

// In a Catch node
if (msg.error && msg.error.includes("BadNodeIdUnknown")) {
// File doesn't exist - create it first
msg.payload = "File Header\n" + msg.payload;
msg.mode = "Write"; // Switch to Write mode
return msg;
}

See Also