Unexpected behavior with contentLib.getAttachmentStream


#1

Enonic version: 6.15.2
OS: Mac

I tried getting an attachment stream and then trying to make sure it exists before I start trying to read it.

var stream = contentLib.getAttachmentStream({
    key: '/path/to/mycontent',
    name: 'myCSVFile.csv'
});

if (!stream || stream === undefined || !stream.exists()) {
    siteLib.log('no stream');
    return [];
} else {
    ioLib.processLines(stream, function(line) {
        if (line) {
            var lineContent = line.split(',');
            ...
        }
});

The problem is that I get an error that “stream.exists” is not a function.
It should fail at !stream and fail again at stream === undefined but it doesn’t. It goes all the way to !stream.exists() and then shows the error.
When I comment out the line with the if statement then it works and I can read the lines.
The documentation for ioLib has the exists() function for stream and I assumed the contentLib.getAttachmentStream() would also return a stream with the exists() function.


#2

There is no exists method in the Stream object. In io-lib there is an exists method but for Resource objects.

Resources are files with a path, located inside the app.
Streams are more general binary objects, often stored inside a Content or Node. Streams don’t have a path, it’s just the data. If you get back a stream object that means it can be read.

In your case you should just check if the value returned is null/undefined or not.

if (!stream) {
    siteLib.log('no stream');
    return [];
} else {
  ...