Qiniu Cloud SDK for Node.js

repository·master·Indexed 20 days ago

https://github.com/qiniu/nodejs-sdk

A Node.js wrapper for the Qiniu Resource (Cloud) Storage API (version 7.15.5). It provides tools for interacting with Qiniu Cloud services, including server-side uploads via FormUploader and ResumeUploader, resource management using BucketManager (stat, move, copy, delete), and the generation of upload tokens (Uptokens) for web and mobile clients. The SDK supports Promise-style asynchronous APIs for storage operations and includes utilities for authenticating requests with Access and Secret Keys.

Tokens
15.6K
Snippets
50
Records
59
Agent score
69%

What's inside qiniu-nodejs-sdk

  1. Use Promise-style APIs for storage operations

    master

    The SDK's storage-related APIs support Promise-style asynchronous code. This includes classes such as BucketManager, FormUploader, and ResumeUploader.

    While the original Callback-style APIs are still supported, it is highly recommended to switch to the Promise-style API to ensure future compatibility.

    Note on Callbacks: If you continue using the Callback style, be aware that errors produced within the callbackFunc will no longer be thrown to the upper layers. You must handle all errors internally within the callbackFunc.

  2. Initialize the CDN Manager

    master

    To use CDN-related features (such as URL/directory refreshing, prefetching, or bandwidth monitoring), you must first instantiate a CdnManager using your access key and secret key.

    Available CDN features include:

    • File refreshing
    • Directory refreshing
    • File prefetching
    • Getting domain traffic/bandwidth
    • Getting log download links
    • Building timestamp-based anti-leech access links
    var accessKey = 'your access key';
    var secretKey = 'your secret key';
    var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    var cdnManager = new qiniu.cdn.CdnManager(mac);
  3. Initialize BucketManager for resource management

    master

    To perform resource management operations (stat, move, copy, delete, etc.), you must first instantiate a qiniu.rs.BucketManager using a Mac object for authentication and a qiniu.conf.Config object for configuration.

    const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    const config = new qiniu.conf.Config();
    config.useHttpsDomain = true;
    const bucketManager = new qiniu.rs.BucketManager(mac, config);
  4. Authenticate with Qiniu using Access Key and Secret Key

    master

    All functions in the Qiniu Node.js SDK require valid authorization. You must use a pair of Access Key and Secret Key associated with your Qiniu account to sign requests.

    To obtain your keys:

    1. Register a Qiniu developer account.
    2. Log in to the Qiniu developer console and navigate to the key management section to view your Access Key and Secret Key.
  5. Download the Qiniu Node.js SDK from releases or git

    master

    If you cannot use npm, you can obtain the SDK through the following methods:

    1. Release Versions: Download stable, versioned releases from the GitHub releases page. These versions are stable and include a CHANGELOG.
    2. Git Repository: You can git clone the source code directly. Note that code in non-master branches may change frequently and should be used with caution.
  6. Configure the FormUploader and ResumeUploader

    master

    For server-side direct uploads, you must first create a qiniu.conf.Config object. This object defines the storage region and other upload parameters.

    While the zone property is deprecated, it is still supported for compatibility. It is recommended to use regionsProvider instead, which is set via qiniu.httpc.Region.fromRegionId(regionId).

    const config = new qiniu.conf.Config();
    // Specify the region using a Region ID (e.g., 'z0' for East China-Zhejiang)
    config.regionsProvider = qiniu.httpc.Region.fromRegionId('z0');
  7. Generate client upload tokens (Uptokens)

    master

    When clients (Web or Mobile) upload files, they must obtain an upload token from your business server. This token is generated using the Node.js SDK and then distributed to the client.

    To generate any token, you must first create a mac authentication object using your AccessKey and SecretKey.

    const accessKey = 'your access key';
    const secretKey = 'your secret key';
    const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
  8. Generate a token with upload callback

    master

    To notify your business server after a client upload completes, use callbackUrl and callbackBody.

    • callbackUrl: The endpoint on your server that Qiniu will POST to.
    • callbackBody: The template for the POST body. It is recommended to use application/json for consistency.
    • callbackBodyType: The content type of the callback body.
    // JSON format callback
    const optionsJson = {
      scope: bucket,
      callbackUrl: 'http://api.example.com/qiniu/upload/callback',
      callbackBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}',
      callbackBodyType: 'application/json'
    };
    const putPolicyJson = new qiniu.rs.PutPolicy(optionsJson);
    const uploadTokenJson = putPolicyJson.uploadToken(mac);
    
    // URL-encoded format callback
    const optionsUrlEncoded = {
      scope: bucket,
      callbackUrl: 'http://api.example.com/qiniu/upload/callback',
      callbackBody: 'key=$(key)&hash=$(etag)&bucket=$(bucket)&fsize=$(fsize)&name=$(x:name)'
    };
    const putPolicyUrl = new qiniu.rs.PutPolicy(optionsUrlEncoded);
    const uploadTokenUrl = putPolicyUrl.uploadToken(mac);
  9. Generate a token with custom return body

    master

    By default, Qiniu returns a JSON containing hash and key. You can customize this response using the returnBody parameter in PutPolicy. You can use magic variables (like $(key), $(etag), $(fsize)) and custom variables (prefixed with x:) to define the JSON structure.

    const options = {
      scope: bucket,
      returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
    };
    const putPolicy = new qiniu.rs.PutPolicy(options);
    const uploadToken = putPolicy.uploadToken(mac);
  10. Generate a token with persistent data processing

    master

    You can trigger data processing (like video transcoding) immediately after upload by specifying persistentOps in the upload policy.

    • persistentOps: A semicolon-separated string of processing instructions.
    • persistentPipeline: The name of the processing queue (must be created in the Qiniu portal).
    • persistentNotifyUrl: The URL to notify when processing is complete.
    const saveMp4Entry = qiniu.util.urlsafeBase64Encode(bucket + ":avthumb_test_target.mp4");
    const saveJpgEntry = qiniu.util.urlsafeBase64Encode(bucket + ":vframe_test_target.jpg");
    
    // Combine multiple instructions
    const avthumbMp4Fop = "avthumb/mp4|saveas/" + saveMp4Entry;
    const vframeJpgFop = "vframe/jpg/offset/1|saveas/" + saveJpgEntry;
    
    const options = {
      scope: bucket,
      persistentOps: avthumbMp4Fop + ";" + vframeJpgFop,
      persistentPipeline: "video-pipe",
      persistentNotifyUrl: "http://api.example.com/qiniu/pfop/notify",
    };
    const putPolicy = new qiniu.rs.PutPolicy(options);
    const uploadToken = putPolicy.uploadToken(mac);