How To

How do I write to a file using JavaScript on a custom endpoint in IDM/OpenIDM (All versions)?

Last updated Jul 9, 2018

The purpose of this article is to provide examples of writing to a local file using JavaScript® on a custom endpoint in IDM/OpenIDM. This article assumes you have already created your custom endpoint.


1 reader recommends this article

Overview

IDM/OpenIDM uses Mozilla® Rhino v1.7R4, which is an embedded Java® implementation of a JavaScript engine. This implementation allows you to execute JavaScript used by endpoints, inline code etc in IDM/OpenIDM.

Writing to a file using JavaScript examples

Here are two examples of how you can write to a file using JavaScript by calling Java from Rhino:

// Verify that the file exists and if not, create it
var fileObj = new java.io.File("/path/to/myfile/file.txt");
if (!fileObj.exists()) {
fileObj.createNewFile();
}

// Create a filewriter object, then append a line to the file and close the file
var fileWriter = new java.io.FileWriter("/path/to/myfile/file.txt", true); // true = append
var logData = "Test\n";
fileWriter.write(logData);
fileWriter.close();

Or a more efficient version:

var content = new java.lang.String("some string" +
java.lang.System.lineSeparator());
java.nio.file.Files.write(
  java.nio.file.Paths.get("logs/mylog.log"),
  content.getBytes(),
  java.nio.file.StandardOpenOption.CREATE,
  java.nio.file.StandardOpenOption.APPEND
);

See Also

How do I load JavaScript functions into IDM/OpenIDM (All versions)?

How do I add logging to JavaScript files in IDM/OpenIDM (All versions)?

How do I debug server-side JavaScript code in OpenIDM 3.x and 4.x?

FAQ: Scripts in IDM/OpenIDM

Integrator's Guide › Extending Functionality By Using Scripts › Creating Custom Endpoints to Launch Scripts

Samples Guide › Creating a Custom Endpoint

Connector Developer's Guide

Rhino documentation

Related Issue Tracker IDs

N/A



Copyright and TrademarksCopyright © 2018 ForgeRock, all rights reserved.
Loading...