LibraryClient SDK
The LibraryClient SDK provides secure access to your project's file library from within code nodes. List, upload, download, and manage files programmatically in your JavaScript or Python workflows.
Overview
The Library Client is automatically available in all code nodes and requires no additional configuration. It uses secure execution tokens that are scoped to your project.
Key Features:
- List and discover files and directories
- Upload files with metadata
- Download files for processing
- Delete files
- Auto-authenticated (no API keys needed)
Installation
The SDK is pre-installed in all code execution environments. No installation required.
Code Structure
Code nodes run as standalone scripts, so you need to structure your code correctly:
JavaScript — await cannot be used at the top level. Wrap your code in an async function:
const { LibraryClient } = require('@intellectible/execution-sdk');
async function main() {
const library = new LibraryClient();
const files = await library.listFiles();
// ... your logic here
}
main().catch(err => console.error(err));
Python — SDK methods are synchronous (no async/await needed). Use a main() function with __main__ guard:
from intellectible_execution import LibraryClient
def main():
library = LibraryClient()
files = library.list_files()
# ... your logic here
if __name__ == '__main__':
main()
All method examples below show just the SDK calls for brevity. In your code node, wrap them inside main() as shown above.
Quick Reference
JavaScript
const { LibraryClient } = require('@intellectible/execution-sdk');
const library = new LibraryClient();
| Method | Returns | Description |
|---|---|---|
listFiles(path?) | FileMetadata[] | List files, optionally filter by directory |
listDirs(path?) | DirMetadata[] | List directories, optionally filter by path |
createDownloadUrl(fileId) | string | Get a signed download URL |
uploadFile(name, fileType, content, path?) | string | Upload a file, returns document ID |
deleteFile(fileId) | void | Delete a file |
Python
from intellectible_execution import LibraryClient
library = LibraryClient()
| Method | Returns | Description |
|---|---|---|
list_files(path?) | List[Dict] | List files, optionally filter by directory |
list_dirs(path?) | List[Dict] | List directories, optionally filter by path |
create_download_url(file_id) | str | Get a signed download URL |
upload_file(name, file_type, content, path?) | str | Upload a file, returns document ID |
delete_file(file_id) | None | Delete a file |
JavaScript SDK
Import
const { LibraryClient } = require('@intellectible/execution-sdk');
const library = new LibraryClient();
Methods
listFiles(path?)
List files in the project library. Optionally filter by directory path.
Parameters:
path(string, optional): Directory path to list files from (default: root). Use folder names separated by/to navigate nested directories.
Returns: Promise<Array<FileMetadata>>
Example:
// List all files at root
const files = await library.listFiles();
console.log(`Found ${files.length} files`);
files.forEach(file => {
console.log(`- ${file.name} (${file.type})`);
});
// List files in a specific folder
const reportFiles = await library.listFiles('reports');
// List files in a nested folder
const q1Files = await library.listFiles('reports/2024/Q1');
Response:
[
{
id: "doc_abc123",
name: "report.pdf",
type: "application/pdf",
size: 245678,
dir: "root",
createdDate: "2025-01-15T10:30:00Z",
updatedDate: "2025-01-15T10:30:00Z"
},
// ... more files
]
listDirs(path?)
List directories in the project library. Optionally filter by path.
Parameters:
path(string, optional): Directory path to list from (default: root). Use folder names separated by/to navigate nested directories.
Returns: Promise<Array<DirMetadata>>
Example:
// List top-level folders
const dirs = await library.listDirs();
console.log('Folders:');
dirs.forEach(dir => {
console.log(`- ${dir.name}`);
});
// List subfolders inside 'reports'
const subDirs = await library.listDirs('reports');
createDownloadUrl(fileId)
Get a signed download URL for a file.
Parameters:
fileId(string, required): The file ID fromlistFiles()
Returns: Promise<string> - Signed download URL
Example:
const files = await library.listFiles();
const fileId = files[0].id;
const downloadUrl = await library.createDownloadUrl(fileId);
// Download the file content
const response = await fetch(downloadUrl);
const fileContent = await response.text();
console.log('File content:', fileContent);
Notes:
- The URL is a 302 redirect to Google Cloud Storage
- URL is signed and expires after a short time
- Use immediately after receiving
uploadFile(name, fileType, content, path?)
Upload a file to the library. Handles the complete upload process automatically.
Parameters:
name(string, required): Display name for the filefileType(string, required): File extension (e.g.,'csv','json') or MIME type (e.g.,'text/csv'). MIME types are auto-converted to extensions.content(Buffer|string, required): File content to uploadpath(string, optional): Directory path, defaults to root
Returns: Promise<string> - Document ID of the uploaded file
Example:
// Upload a CSV file to root
const csvData = 'name,value\nAlice,100\nBob,200';
const docId = await library.uploadFile('results.csv', 'csv', csvData);
console.log('File uploaded:', docId);
// Upload a JSON file into a specific folder
const report = JSON.stringify({ summary: 'Results', count: 42 });
const docId2 = await library.uploadFile('report.json', 'json', report, 'reports/2024');
Supported File Types:
You can use either file extensions or MIME types:
| Extension | MIME Type |
|---|---|
csv | text/csv |
txt | text/plain |
html | text/html |
json | application/json |
pdf | application/pdf |
xml | application/xml |
zip | application/zip |
parquet | application/vnd.apache.parquet |
docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
pptx | application/vnd.openxmlformats-officedocument.presentationml.presentation |
png | image/png |
jpeg | image/jpeg |
gif | image/gif |
webp | image/webp |
svg | image/svg+xml |
deleteFile(fileId)
Delete a file from the library.
Parameters:
fileId(string, required): The file ID to delete
Returns: Promise<void>
Example:
const files = await library.listFiles();
const oldFileId = files.find(f => f.name === 'old-report.pdf')?.id;
if (oldFileId) {
await library.deleteFile(oldFileId);
console.log('File deleted successfully');
}
Warning: Deletion is permanent and cannot be undone.
Python SDK
Import
from intellectible_execution import LibraryClient
library = LibraryClient()
Methods
list_files(path=None)
List files in the project library. Optionally filter by directory path.
Parameters:
path(str, optional): Directory path to list files from (default: root). Use folder names separated by/to navigate nested directories.
Returns: List[Dict]
Example:
# List all files at root
files = library.list_files()
print(f'Found {len(files)} files')
for file in files:
print(f'- {file["name"]} ({file["type"]})')
# List files in a specific folder
report_files = library.list_files('reports')
# List files in a nested folder
q1_files = library.list_files('reports/2024/Q1')
list_dirs(path=None)
List directories in the project library. Optionally filter by path.
Parameters:
path(str, optional): Directory path to list from (default: root). Use folder names separated by/to navigate nested directories.
Returns: List[Dict]
Example:
# List top-level folders
dirs = library.list_dirs()
print('Folders:')
for d in dirs:
print(f'- {d["name"]}')
# List subfolders inside 'reports'
sub_dirs = library.list_dirs('reports')
create_download_url(file_id)
Get a signed download URL for a file.
Parameters:
file_id(str, required): The file ID fromlist_files()
Returns: str - Signed download URL
Example:
import requests
files = library.list_files()
file_id = files[0]['id']
download_url = library.create_download_url(file_id)
# Download the file content
response = requests.get(download_url)
file_content = response.text
print('File content:', file_content)
upload_file(name, file_type, content, path=None)
Upload a file to the library. Handles the complete upload process automatically.
Parameters:
name(str, required): Display name for the filefile_type(str, required): File extension (e.g.,'csv','json') or MIME type (e.g.,'text/csv'). MIME types are auto-converted to extensions.content(bytes, required): File content as bytespath(str, optional): Directory path, defaults to root. Use folder names separated by/(e.g.,'reports/2024').
Returns: str - Document ID of the uploaded file
Example:
# Upload a CSV file to root
csv_data = 'name,value\nAlice,100\nBob,200'
doc_id = library.upload_file('results.csv', 'csv', csv_data.encode('utf-8'))
print('File uploaded:', doc_id)
# Upload a JSON file into a specific folder
import json
report = json.dumps({'summary': 'Results', 'count': 42})
doc_id = library.upload_file('report.json', 'json', report.encode('utf-8'), 'reports/2024')
delete_file(file_id)
Delete a file from the library.
Parameters:
file_id(str, required): The file ID to delete
Returns: None
Example:
files = library.list_files()
old_file = next((f for f in files if f['name'] == 'old-report.pdf'), None)
if old_file:
library.delete_file(old_file['id'])
print('File deleted successfully')
Common Use Cases
Download and Process CSV
JavaScript:
const { LibraryClient } = require('@intellectible/execution-sdk');
async function main() {
const library = new LibraryClient();
// Find CSV file
const files = await library.listFiles();
const csvFile = files.find(f => f.type === 'text/csv');
// Download and parse
const downloadUrl = await library.createDownloadUrl(csvFile.id);
const response = await fetch(downloadUrl);
const csvText = await response.text();
// Process CSV (split lines, parse, etc.)
const rows = csvText.split('\n').map(line => line.split(','));
console.log('Parsed rows:', rows.length);
}
main().catch(err => console.error(err));
Python:
import requests
import csv
from io import StringIO
from intellectible_execution import LibraryClient
def main():
library = LibraryClient()
# Find CSV file
files = library.list_files()
csv_file = next(f for f in files if f['type'] == 'text/csv')
# Download and parse
download_url = library.create_download_url(csv_file['id'])
response = requests.get(download_url)
csv_text = response.text
# Process CSV
reader = csv.DictReader(StringIO(csv_text))
rows = list(reader)
print(f'Parsed rows: {len(rows)}')
if __name__ == '__main__':
main()
Generate and Upload Report
JavaScript:
const { LibraryClient } = require('@intellectible/execution-sdk');
async function main() {
const library = new LibraryClient();
// Generate report content
const reportData = {
title: 'Monthly Report',
date: new Date().toISOString(),
metrics: { sales: 15000, customers: 42 }
};
const reportJson = JSON.stringify(reportData, null, 2);
// Upload report (single call handles everything)
const docId = await library.uploadFile('report.json', 'json', reportJson);
console.log('Report uploaded:', docId);
}
main().catch(err => console.error(err));
Python:
import json
from datetime import datetime
from intellectible_execution import LibraryClient
def main():
library = LibraryClient()
# Generate report content
report_data = {
'title': 'Monthly Report',
'date': datetime.now().isoformat(),
'metrics': {'sales': 15000, 'customers': 42}
}
report_json = json.dumps(report_data, indent=2)
# Upload report (single call handles everything)
doc_id = library.upload_file('report.json', 'json', report_json.encode('utf-8'))
print('Report uploaded:', doc_id)
if __name__ == '__main__':
main()
Error Handling
Both SDKs throw errors for failed operations:
JavaScript:
try {
const files = await library.listFiles();
} catch (error) {
console.error('Failed to list files:', error.message);
}
Python:
try:
files = library.list_files()
except Exception as error:
print(f'Failed to list files: {error}')
Limitations
- Execution timeout: All operations must complete within the 10-minute code node timeout
See Also
- DatabaseClient SDK - Access project databases
- Code Nodes Guide - Overview of code execution
- Code Node Data Access Guide - Conceptual overview