API Reference
This library handles MEGA encryption, file and folder handling and networking. Since this is a library focused on work on multiple platforms (Node.js and browsers) it does not and will not handle file reading, file writing nor any platform-specific file operations.
You should implement file I/O using the functions provided by your platform (like reading files using fs.createReadStream
on Node and <input type="file">
on browsers, and writing using fs.createWriteStream
on Node and <a download>
on browsers).
Promises
Promise support was added in V1. All functions which used to accept callbacks now also accept promises, except by:
new Storage()
: the promise is available in the.ready
property;.upload()
: the promise is available in the.complete
property;.download()
: call.downloadBuffer()
instead;
Entry point
The exported classes and functions are those below:
Storage
classFile
classfile
: alias toFile.fromURL
API
classencrypt
,decrypt
andverify
(low level encryption streams)
Storage
Creates a logged in connection instance to MEGA.
Creation
- Node ESM
- Node CJS
- Browser
- Deno
import { Storage } from 'megajs'
const storage = new Storage(options, [callback])
const { Storage } = require('megajs')
const storage = new Storage(options, [callback])
import { Storage } from 'https://unpkg.com/megajs/dist/main.browser-es.mjs'
const storage = new Storage(options, [callback])
import { Storage } from 'npm:megajs'
const storage = new Storage(options, [callback])
Options
email
- User login email required.password
- User password required.secondFactorCode
- User two-factor authentication code (since 1.2.0).keepalive
- Keep connection open to receive server-to-client requests that will be mapped to events. Defaults totrue
.autologin
- Logins to MEGA. Defaults totrue
. Set tofalse
if you want to change request options, like proxy, like shown here.autoload
- Load in file structure. Defaults totrue
.api
- an API object.- All arguments supported by the API class (in case an API object is not provided).
Temporary accounts aren't supported. Trying to login without an email or password will throw an error.
Properties
Only loaded after .resolve
, readyCallback()
or ready
event fires.
name
- Account owner nameuser
- Account IDkey
- Account master keysid
- Current session IDfiles
- Hash ofMutableFile
objects by node IDs.root
-MutableFile
object for Cloud Drive main directorytrash
-MutableFile
object for Rubbish bininbox
-MutableFile
object for Inboxmounts
- Array of all top level directories
Methods
Shorthands
.upload
maps tostorage.root.upload
..mkdir
maps tostorage.root.mkdir
..find
maps tostorage.root.find
..filter
maps tostorage.root.filter
..navigate
maps tostorage.root.navigate
.
.reload()
Reloads files tree. No need to call this if autoload
is used.
.login()
Logins to MEGA. No need to call this if autologin
is used.
.getAccountInfo()
Get info related to account and quota usage. It returns a object with the following properties:
type
: the account typespaceUsed
: the space used by the account, in bytesspaceTotal
: the total space available, in bytesdownloadBandwidthUsed
: the bandwidth quota used, in bytesdownloadBandwidthTotal
: the total bandwidth quota available, in bytessharedBandwidthUsed
: the shared bandwidth quota used, in bytessharedBandwidthLimit
: the total shared bandwidth quota available, in bytes
.close()
Logs out MEGA and closes server-to-client connection. Other connections will not be closed. Attempting to call API requests after this point will result in errors.
Events
These events fire on file changes when keepalive
is used. The changes can be triggered from any session connected to the same account.
add
- New file/dir was added. Parameters: file.move
- File was moved to another dir. Parameters: file, olddir.delete
- File was deleted. Parameters: file.update
- File was changed(renamed). Parameters: file.
File
Basic class that handle files and folders. Often used to handle shared files and folders.
Creation
- Node ESM
- Node CJS
- Browser
- Deno
import { File } from 'megajs'
const fileFromUrl = File.fromURL(url)
const fileFromObject = new File({ downloadId, key })
const { File } = require('megajs')
const fileFromUrl = File.fromURL(url)
const fileFromObject = new File({ downloadId, key })
import { File } from 'https://unpkg.com/megajs/dist/main.browser-es.mjs'
const fileFromUrl = File.fromURL(url)
const fileFromObject = new File({ downloadId, key })
import { File } from 'npm:megajs'
const fileFromUrl = File.fromURL(url)
const fileFromObject = new File({ downloadId, key })
To avoid collisions with the global File
object you can use import { File as MEGAFile } from 'megajs'
or const { File: MEGAFile } = require('megajs')
and use MEGAFile
instead of File
.
Options
If a string is passed it needs to be a shared MEGA URL. It can be a https://mega.co.nz
or a https://mega.nz
file. The new URL format with /file/
or /folder/
is also supported.
If an object is passed it needs to have the options below:
downloadId
: https://mega.nz/file/THIS_PART#...` of the share link; a string.key
:https://mega.nz/file/...#THIS_PART
of the share link; string or a Buffer; optional.directory
:true
if loading a shared folder.
Both new File
and File.fromURL
supports receiving either an API object via api
argument like this:
const fileFromUrl = File.fromURL(url, { api })
const fileFromObject = new File({ downloadId, key, api })
This allows using an logged API object to increase download limits, as shown here.
Properties
name
- File name*attributes
- Object of attributes*size
- File sizekey
- File key (buffer)*timestamp
- File creation time (unix timestamp in seconds)nodeId
- File IDdownloadId
- Link ID to file. Only if created from link.directory
- Boolean if file is directory.children
- Array of files for directories.
Values marked with * are null
or undefined
when an encryption key isn't specified. An encryption key isn't specified when someone loads a shared file without specifying the encryption key like File.fromURL('https://mega.nz/file/something')
without the #random-string
part. Files loaded from accounts always have keys defined.
Methods
.loadAttributes()
Load and decrypt file attributes. Attributes normally contain file name ('n'
) but is possible to put anything there, as long it can be encoded as JSON. Isn't needed for files loaded from logged sessions. Trying to call it in a MutableFile
will throw an error.
await file.loadAttributes()
file.loadAttributes((err, file) => { })
This function can be also be used to load file information contained in shared folders.
.download([options], [callback])
Download and decrypt file contents into a readable stream or, if a callback is specified, into a buffer.
file.download().pipe(fs.createWriteStream('myfile.txt'))
file.download((err, data) => {
// data is buffer
})
This function downloads files using chunked multiple parallel connections to speed up downloading. Similar to the MEGA implementation it first loads a 128KB chunk, then a 256KB, increasing it until it reaches 1MB. You can use the options below to control that.
maxConnections
: the number of parallel connections is defined (default: 4);initialChunkSize
: first chunk size, in bytes (default: 128KB);chunkSizeIncrement
: how many bytes to increment each time (default: 128KB);maxChunkSize
: maximum chunk size, in bytes (max 1MB);returnCiphertext
: iftrue
the ciphertext will be returned, which can be decrypted later usingdecrypt
low level function.handleRetries
: accepts a function to handle retries on chunk downloading errors, overrides the function defined byFile.defaultHandleRetries
;forceHttps
: if set totrue
will download using HTTPS, if set tofalse
will download using HTTP. Default tofalse
in the Node build andtrue
in the browser build or if aDeno
global is set.
The download function also support start
and end
options, like fs.createReadStream
.
If the number of connections get limited to 1
then chunking will be disabled and the entire file will be downloaded using a single connection. For some reason doing this often results in less connection errors. At the moment this feature relies on a node-fetch extension and might not work in non-Node environments.
You can get progress events from the progress
event which will contain the following properties:
bytesLoaded
: the number of bytes loaded;bytesTotal
: the total number of bytes of the file;
.downloadBuffer([options])
Wraps the .download()
function and return a Promise which resolves to a Buffer containing the file data. Accept the same options as .download()
. It still accepts a callback, but then it's better to call .download()
to avoid creating an unneeded promise.
.find(query, [deep])
Search for files in directores, recursively if the deep argument is true
. Queries might be strings (which matches names, case sensitive), arrays of valid names (case sensitive) or a function which receives a MutableFile object as argument and should return a boolean.
// Returns a file named `test.txt` inside the folder or undefined if no file gets found
folder.find('test.txt')
// Returns a file named `test.txt` inside the folder while searching recursively
folder.find('test.txt', true)
// Returns the first file with a size larger than 1024 bytes
folder.find(file => file.size > 1024)
.filter(query, [deep])
Filters for files in directores, recursively if the deep argument is true
. Queries might be strings (which matches names, case sensitive), arrays of valid names (case sensitive) or a function which receives a MutableFile object as argument and should return a boolean.
// Returns an array with all files named `test.txt` inside the folder
folder.filter('test.txt')
// Returns an array with all files named `test.txt` while searching recursively
folder.filter('test.txt', true)
// Returns an array with all files with a size larger than 1024 bytes
folder.filter(file => file.size > 1024)
.navigate(query)
Traverses directories. Query can be a string with a /
delimited path or an array of strings. Names are matched case sensitive.
// Returns a file named `test.txt` inside "some folder"
folder.navigate('some folder/test.txt')
// Paths can also be defined as arrays of strings
folder.navigate(['some folder', 'test.txt'])
Static methods
File.fromURL(url, [options])
Creates a File object based on a shared file or folder URL. Accepts an optional options object with an api
object.
File.defaultHandleRetries(tries, error, cb)
Default function used by File.protoype.download
and MutableFile.protoype.upload
to handle chunk downloading or upload should be retried on errors. Receives as arguments number of retries, the last error and a callback function.
This function can be overridden. Example:
// Default retry handler
File.defaultHandleRetries = (tries, error, cb) => {
if (tries > 8) {
cb(error)
} else {
setTimeout(cb, 1000 * Math.pow(2, tries))
}
}
// Restore behavior from V0
File.defaultHandleRetries = (tries, error, cb) => {
cb(error)
}
Mutable File
Represents files and folders that the current user can change in some way (like renaming). Extends File
adding methods that are only available when logged in.
Please note: what are mutable are the attributes of the files and folders, not their contents, as this library don't support this yet.
Basic syntax
Those objects can be only accessed when logged in and can only be accessed via the Storage
object.
// Returns the first file in the root of the storage
storage.root.children[0]
// Returns a file named "test.txt" in the root of the storage
storage.find('test.txt')
Methods
.upload(options | name, [data], [callback])
const uploadedFile = await folder.upload('myfile.txt', 'Hello world!').complete
fs.createReadStream('myfile.txt').pipe(folder.upload('myfile.txt'))
folder.upload('myfile.txt', 'Hello world!', (error, uploadedFile) => {})
Upload a file to a folder.
To input data you can input a buffer, string or stream in the data argument or, as it returns a stream, pipe data into it.
To handle upload completion or errors you can:
- Await for the promise returned by
.complete
. - Use the callback, which will return either an error as its first argument or the uploaded file instance as its second.
- Listen for
complete
anderror
events.
Supported options:
name
: file name, requiredattributes
: object of file attributeskey
: encryption key, Buffer or string; 192 bit; because MAC verification part of it be different in final keysize
: file size, required unlessallowUploadBuffering
is set to true.thumbnailImage
: the Buffer or Stream of the thumbnail imagepreviewImage
: the Buffer or Stream of the preview imagemaxConnections
: the number of parallel connections is defined (default: 4);initialChunkSize
: first chunk size, in bytes (default: 128KB);chunkSizeIncrement
: how many bytes to increment each time (default: 128KB);maxChunkSize
: maximum chunk size, in bytes (max 1MB);handleRetries
: accepts a function to handle retries on chunk downloading errors, overrides the function defined byFile.defaultHandleRetries
;forceHttps
: if set totrue
will upload using HTTPS, if set tofalse
will upload using HTTP. Default tofalse
in the Node build andtrue
in the browser build or if aDeno
global is set.
Thumbnail images are 120px x 120px JPEG images with 70% quality. Preview images are JPEG images with a maximum width and height size of 1000px and 75% quality. Please use those settings to avoid breaking compatibility with other MEGA clients. This library don't generates neither preview or thumbnail images, only provides a way to uploading those.
Uploading data without encryption is supported and is documented here.
The upload stream is always returned even when a callback is specified. Standard events for Writable Streams, like error
and finish
, and methods, like .pipe()
and .write()
, work normally.
.mkdir(options | name)
await folder.mkdir('dirname')
Create a new folder inside the current folder.
Supported options:
name
: directory name, requiredattributes
: object of file attributeskey
: encryption key, Buffer or string; 128 bit; only used internally (when sharing folders other key is used)
.importFile(File | URL)
Import a file to the specified folder. It accepts File objects (from new File
) or URLs of shared files.
// Returns an instance of MutableFile
const file = await folder.importFile('https://mega.nz/#!...')
.link([options])
/ .shareFolder([options])
Make download link for a file or folder. .shareFolder
only works for folders, .link
works for both (but calls .shareFolder
internally).
// Returns something like https://mega.nz/#!downloadId!key
const url = await file.link()
Supported options:
noKey
: settrue
to return a url without an encryption keykey
: only works for folders, encryption key, can be a string or buffer, 128 bit
.unshare()
/ .unshareFolder()
Unshares files and folders. .unshareFolder
only works for folders, .unshare
works for both (but calls .unshareFolder
internally).
.delete(permanent)
Delete file, permanently if permanent
is true, otherwise file is moved to rubbish bin.
// Moves the file to rubbish bin
await file.delete()
// Deletes the file permanently
await file.delete(true)
.moveTo(target)
Move a file to target, which can be a folder object or it's nodeId.
// Moves the file to storage root
await file.moveTo(storage.root)
.setAttributes(attributes)
Set the the attributes of a object. Doesn't remove the current ones, but can overwrite those.
await file.setAttributes({someAttribute: someValue})
.uploadAttribute(type, [buffer|stream])
Upload a thumbnail or preview image to the existent file. Fails if the node is a folder.
The argument type
can be a string (thumbnail
or preview
) or a integer (0
and 1
).
.rename(newFileName)
Rename a file.
await file.rename('hello-world.txt')
.setLabel(label)
Set file's label, where label
can be a number between 0 and 7 or a valid label color the following: 'red', 'orange', 'yellow', 'green', 'blue', 'purple' and 'grey'.
await file.setLabel('red')
.setFavorite(isFavorite)
Set file as favorite is isFavorite
is true
await file.setFavorite(true)
await file.setFavorite(false)
Events
Same events as for Storage objects. Only trigger for a specific file.
move
- File was moved to another dir. Parameters: olddir.delete
- File was deleted.update
- File metadata was changed.
API
The API class handles API connections, which includes part of the logged state, user-agent, HTTP/HTTPS agents (for proxying).
Properties
gateway
- the gateway used to connect to MEGA's API, defaults tohttps://g.api.mega.co.nz/
.userAgent
- the user-agent used when connecting.httpAgent
andhttpsAgent
- the HTTP(S) agents used in Node, can be overriden to enable proxying;fetch
- the fetch function used by library, defaults tonode-fetch
in Node andglobalThis.fetch
in other environments;
If the fetch
function is overridden then the userAgent
, httpAgentand
httpsAgent` properties will be ignored.
It is recommended to set up an user-agent. The library will default to megajs/{version}
(where {version}
is the library version). When deploying to browsers set userAgent
to null
as it can cause issues in some browsers which allow client-side code to override the user-agent
header (i.e. Firefox).