MEGAJS JavaScript SDK

repository·next·Indexed 41 days ago

https://github.com/qgustavor/mega

An unofficial, modernized JavaScript SDK for interacting with MEGA cloud storage. Version 1.3.10 provides a lightweight, multi-runtime alternative (Node.js, Deno, and Browser) to original MEGA libraries, featuring built-in TypeScript support and improved browser compatibility.

Tokens
11.3K
Snippets
47
Records
51
Agent score
51%

What's inside MEGAJS

  1. Overview of MEGAJS

    next

    MEGAJS is an unofficial JavaScript SDK for MEGA, based on tonistiigi/mega. It is designed to work in modern environments including browsers, Node.js, and Deno.

    Key improvements over the original library include:

    • Browser Compatibility: Fixed issues with non-standard __proto__ usage to ensure stability in modern browsers and Service Workers.
    • Reduced Dependencies: Replaced large dependencies (like heavy crypto libraries) with smaller, more efficient alternatives.
    • Modern Syntax: Rewritten using modern JavaScript to allow for smaller bundles via esbuild.
    • Multi-runtime Support: Native support for Node.js and Deno.
    • TypeScript Support: Includes built-in TypeScript types.

    Note: This is an unofficial SDK. Users must comply with MEGA's Terms of Service. For full API documentation and examples, visit https://mega.js.org/.

  2. Initialize the Storage class

    next

    The Storage class is the primary entry point for interacting with MEGA cloud storage. You can initialize it by passing an options object. If autologin is enabled (default), the class will attempt to log in immediately using the provided email and password.

    Because the constructor cannot be asynchronous, it provides a ready property, which is a Promise that resolves when the storage instance is fully initialized and logged in.

    Options:

    • email (string): Your MEGA account email.
    • password (string): Your MEGA account password.
    • autologin (boolean, default: true): Whether to attempt login immediately upon instantiation.
    • autoload (boolean, default: true): Whether to automatically reload the file tree after login.
    • keepalive (boolean, default: true): Whether to maintain the connection.
    • secondFactorCode (string/number): The MFA code if two-factor authentication is enabled.
    ```javascript
    import Storage from './lib/storage.mjs';
    
    const storage = new Storage({
      email: 'user@example.com',
      password: 'your-password',
      autologin: true
    });
    
    // Wait for the storage to be ready
    await storage.ready;
    console.log('Logged in as:', storage.name);
  3. Configure AVA test runner settings

    next

    The ava.config.mjs file is used to configure the AVA test runner. You can specify which files to include in the test suite, set a global timeout for tests, enable failFast mode to stop execution on the first failure, and define which file extensions are treated as test files.

    export default {
      files: [
        'test/**/*.test.mjs'
      ],
      timeout: '20s',
      failFast: true,
      extensions: {
        js: true,
        mjs: true
      }
    }
  4. Handle MEGA bandwidth limit errors

    next

    When downloading, if you encounter a 509 status code, the stream will emit an error indicating the bandwidth limit has been reached. The error object includes a timeLimit property indicating how many seconds remain until the limit resets.

    Error structure:

    • error.message: Bandwidth limit reached: <seconds>
    • error.timeLimit: The number of seconds remaining (as a string).
    stream.on('error', (err) => {
      if (err.timeLimit) {
        console.error(`Limit reached. Try again in ${err.timeLimit} seconds.`);
      } else {
        console.error(err.message);
      }
    });
  5. Create a File instance from a MEGA URL

    next

    Use the static File.fromURL(url, extraOpt) method to create a File instance directly from a MEGA link. This method supports both the old format (using #! and !) and the new format (using /file/ or /folder/ paths).

    Supported Formats:

    • https://mega.nz/file/file_handler#file_key
    • https://mega.nz/folder/folder_handler#folder_key/file/file_handler
    • https://mega.nz/#!file_handler!file_key
    • https://mega.nz/#F!folder_handler!folder_key
    import File from './lib/file.mjs';
    
    const file = File.fromURL('https://mega.nz/file/some-handler#some-key');
  6. Search and filter within a directory

    next

    If the File instance represents a directory (this.directory === true), you can search through its children.

    find(query, deep) Returns the first child that matches the query.

    • query: A string (exact name match), an array of strings (matches any in list), or a predicate function (file) => boolean.
    • deep (boolean): If true, performs a recursive search through subdirectories.

    filter(query, deep) Returns an array of all children that match the query.

    • query: A string, an array of strings, or a predicate function.
    • deep (boolean): If true, performs a recursive search.

    navigate(query) Traverses the directory tree based on a path.

    • query: A string representing a path (e.g., 'folder/subfolder') or an array of names.
    // Find a specific file by name deep in the tree
    const target = folder.find('my-document.pdf', true);
    
    // Filter all files with a specific name
    const matches = folder.filter(['image1.png', 'image2.png']);
    
    // Navigate to a specific subfolder
    const subfolder = folder.navigate('Documents/Work');
  7. Use encryption and decryption transforms

    next

    The megajs namespace provides utility functions to create Node.js Transform streams for handling encrypted data.

    • megajs.encrypt(key, options?): Returns a Transform stream that encrypts data using the provided Buffer key.
    • megajs.decrypt(key, options?): Returns a Transform stream that decrypts data using the provided Buffer key.
    • megajs.verify(key): Returns a Transform stream that verifies data integrity using the provided Buffer key.

    cryptOpts includes:

    • start: Starting offset.
    • disableVerification: Boolean to skip verification steps.
    import megajs from 'megajs';
    import { PassThrough } from 'stream';
    
    const key = Buffer.from('your-32-byte-key-here...');
    const encryptor = megajs.encrypt(key);
    const input = new PassThrough();
    const output = new PassThrough();
    
    input.pipe(encryptor).pipe(output);
    input.write('secret data');
    input.end();
  8. Use megaEncrypt, megaDecrypt, and megaVerify for stream encryption

    next

    The megaEncrypt, megaDecrypt, and megaVerify functions provide stream-based cryptographic operations using the MEGA protocol. These functions return a Transform stream (wrapped with pumpify and chunkSizeSafe) that can be piped into or out of other Node.js streams.

    Encryption (megaEncrypt)

    • Key Requirement: Must be a 192-bit (24-byte) key.
    • Constraint: The start option must be 0. Starting midstream will cause MAC verification to fail during decryption.
    • Behavior: It encrypts data using AES-CTR and computes a MAC. The MAC is merged into the key during the flush phase.

    Decryption (megaDecrypt)

    • Key Requirement: Must be a 24-byte key.
    • Constraint: The start option must be a multiple of 16.
    • Verification: By default, it verifies the MAC. To skip verification, set disableVerification: true in the options object.

    Verification (megaVerify)

    • Key Requirement: Must be a 256-bit (32-byte) key.
    • Behavior: It computes the MAC of the incoming stream and compares it against the trailing bytes of the provided key.
    import { megaEncrypt, megaDecrypt, megaVerify } from './lib/crypto/index.mjs';
    import { createReadStream, createWriteStream } from 'fs';
    
    const key = Buffer.alloc(24, 'a'); // 192-bit key
    
    // Encrypting a file
    createReadStream('input.txt')
      .pipe(megaEncrypt(key))
      .pipe(createWriteStream('input.enc'));
    
    // Decrypting a file
    createReadStream('input.enc')
      .pipe(megaDecrypt(key))
      .pipe(createWriteStream('output.txt'));
  9. Manage files using the Storage class

    next

    The Storage class is the primary entry point for interacting with a MEGA account. It extends EventEmitter and provides methods for file system operations and account management.

    Key Methods:

    • login(cb?): Logs into the account. Returns a Promise<this>.
    • mkdir(opt | string, cb?): Creates a new directory. opt can be a mkdirOpts object or a string name.
    • upload(opt | string, buffer?, cb?): Uploads a file. Returns an UploadStream.
    • getAccountInfo(cb?): Retrieves account usage statistics (space, bandwidth). Returns a Promise<accountInfo>.
    • filter(query, deep?): Returns an array of MutableFile objects matching a query.
    • find(query, deep?): Finds a single MutableFile matching a query.
    • close(cb?): Closes the storage connection. Returns a Promise<void>.
    • toJSON(): Serializes the storage state to StorageJSON for persistence.
    • static fromJSON(json): Reconstructs a Storage instance from StorageJSON.

    Events:

    • ready: Emitted when the storage is fully initialized.
    • add: Emitted when a new file is added.
    • move: Emitted when a file is moved.
    • update: Emitted when a file is updated.
    • delete: Emitted when a file is deleted.
    // Example: Creating a directory and uploading a file
    storage.ready.then(async () => {
      await storage.mkdir({ name: 'my_folder' });
      const upload = storage.upload({ name: 'hello.txt' }, 'Hello World');
      
      upload.complete.then(file => {
        console.log('Upload complete:', file.name);
      });
    });
  10. Manage file sharing and links

    next

    The MutableFile class provides several methods for sharing and linking files/folders:

    • link(options): Generates a public URL for a file or folder. If options.noKey is false, the encryption key is appended to the URL.
    • shareFolder(options): Creates a shareable link for a directory. Requires a 16-byte key in options if not automatically generated.
    • unshare(cb): Removes sharing for a folder or unlinks a file.
    • unshareFolder(cb): Specifically removes sharing for a directory.
    • importFile(sharedFile): Imports a file from a URL or another File object into the current directory.
    // Generate a link for a folder
    const url = await folder.link({ noKey: false });
    
    // Share a folder with a specific key
    const shareUrl = await folder.shareFolder({ key: Buffer.from('16byte_key_here_') });
    
    // Import a shared file into the current directory
    const importedFile = await directory.importFile('https://mega.nz/folder/...');
  11. Modify file metadata and attributes

    next

    You can update file metadata using several specialized methods or the generic setAttributes() method.

    • rename(filename, cb): Changes the file name.
    • setLabel(label, cb): Sets a label (0-7 or a valid LABEL_NAMES string).
    • setFavorite(isFavorite, cb): Sets the favorite status.
    • setAttributes(attributes, cb): Performs a bulk update of the file's attributes object.
    // Rename a file
    await file.rename('new_name.txt');
    
    // Set a label
    await file.setLabel('important');
    
    // Set favorite status
    await file.setFavorite(true);
  12. Encode and decode URL-safe Base64 with e64 and d64

    next

    Use e64 for URL-safe Base64 encoding and d64 for decoding. URL-safe encoding replaces + with -, / with _, and removes padding (=).

    import { e64, d64 } from './lib/crypto/index.mjs';
    
    const buf = Buffer.from('hello');
    const encoded = e64(buf); // 'aGVsbG8'
    const decoded = d64(encoded); // <Buffer 68 65 6c 6c 6f>