IO Library
Contents
IO related functions.
Usage
Add the following to your build.gradle
file:
dependencies {
include "com.enonic.xp:lib-io:${xpVersion}"
}
In your JavaScript controller, add a require statement:
var ioLib = require('/lib/xp/io');
You are now ready to use the library functionality.
Functions
getMimeType
Returns the mime-type from a name or extension.
Parameters
Name | Type | Description |
---|---|---|
name |
string |
Name of file or extension |
Returns
string : mime-type from a name or extension.
Example
// Returns mime-type for a file name.
var type = ioLib.getMimeType('myfile.txt');
log.info('Mime type is %s', type);
getResource
Looks up a resource.
Parameters
Name | Type | Description |
---|---|---|
key |
string |
Resource key to look up |
Returns
Resource : Resource reference.
Examples
// Returns a file by name.
var res1 = ioLib.getResource('/lib/xp/examples/io/sample.txt');
var exists = res1.exists();
var size = res1.getSize();
var stream = res1.getStream();
// Returns a file by reference.
var res2 = ioLib.getResource(resolve('./sample.txt'));
if (res2.exists()) {
log.info('Resource exists');
}
getSize
Returns the size of a stream.
Parameters
Name | Type | Description |
---|---|---|
stream |
Stream to get size of |
Returns
number : Returns the size of a stream.
Example
// Returns the size of a stream.
var size = ioLib.getSize(stream);
log.info('Stream size is %s bytes', size);
newStream
Returns a new stream from a string.
Parameters
Name | Type | Description |
---|---|---|
text |
string |
String to create a stream of |
Returns
* : A new stream.
Example
// Creates a new stream from a string.
var stream = ioLib.newStream('Hello World');
processLines
Process lines from a stream.
Parameters
Name | Type | Description |
---|---|---|
stream |
Stream to read lines from |
|
func |
function |
Callback function to be called for each line |
Example
var num = 0;
// Process lines from stream.
ioLib.processLines(stream, function (line) {
num++;
log.info('Line %s: %s', num, line);
});
readLines
Read lines from a stream.
Parameters
Name | Type | Description |
---|---|---|
stream |
Stream to read lines from |
Returns
string[] : Lines as an array.
Example
// Reads lines from stream.
var lines = ioLib.readLines(stream);
log.info('Num lines: %s', lines.length);
readText
Read text from a stream.
Parameters
Name | Type | Description |
---|---|---|
stream |
Stream to read text from |
Returns
string : The text read from stream or string.
Example
// Reads text from stream.
var text = ioLib.readText(stream);
log.info('Text: %s', text);