### Install Node.js SDK Source: https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md Install the Qiniu Node.js SDK using npm. This is the recommended method for integrating the SDK into your project. ```bash $ npm install qiniu ``` -------------------------------- ### Install Qiniu SDK via npm Source: https://github.com/qiniu/nodejs-sdk/blob/master/README.md This is the recommended method for installing the Qiniu SDK for Node.js. ```bash npm install qiniu ``` -------------------------------- ### Authentication Setup Source: https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md Initialize the authentication object using your Access Key and Secret Key. This object is required for generating upload tokens and performing other authenticated operations. ```APIDOC ## Authentication Setup ### Description Initialize the authentication object using your Access Key and Secret Key. This object is required for generating upload tokens and performing other authenticated operations. ### Code ```javascript const accessKey = 'your access key'; const secretKey = 'your secret key'; const mac = new qiniu.auth.digest.Mac(accessKey, secretKey); ``` ``` -------------------------------- ### 获取域名带宽 (Get Domain Bandwidth Data) Source: https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md Retrieves bandwidth data for specified domains within a given date range and granularity. ```APIDOC ## 获取域名带宽 (Get Domain Bandwidth Data) ### Description Retrieves bandwidth data for specified domains within a given date range and granularity. ### Method `cdnManager.getBandwidthData(startDate, endDate, granularity, domains, callback)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **startDate** (string) - Required - The start date for the data retrieval (YYYY-MM-DD). - **endDate** (string) - Required - The end date for the data retrieval (YYYY-MM-DD). - **granularity** (string) - Required - The granularity of the data ('day', 'hour'). - **domains** (Array) - Required - A list of domain names to retrieve data for. - **callback** (Function) - Required - A callback function that handles the response. - **err**: Error object if an error occurred. - **respBody**: The response body from the server. - **respInfo**: Information about the response, including status code. ### Request Example ```javascript //域名列表 var domains = [ 'if-pbl.qiniudn.com', 'qdisk.qiniudn.com' ]; //指定日期 var startDate = '2017-06-20'; var endDate = '2017-06-22'; var granularity = 'day'; //获取域名带宽 cdnManager.getBandwidthData(startDate, endDate, granularity, domains, function( err, respBody, respInfo) { if (err) { console.log(err); throw err; } console.log(respInfo.statusCode); if (respInfo.statusCode == 200) { var jsonBody = JSON.parse(respBody); var code = jsonBody.code; console.log(code); var tickTime = jsonBody.time; console.log(tickTime); var bandwidthData = jsonBody.data; domains.forEach(function(domain) { var bandwidthDataOfDomain = bandwidthData[domain]; if (bandwidthDataOfDomain != null) { console.log("bandwidth data for:" + domain); var bandwidthChina = bandwidthDataOfDomain["china"]; var bandwidthOversea = bandwidthDataOfDomain["oversea"]; console.log(bandwidthChina); console.log(bandwidthOversea); } else { console.log("no bandwidth data for:" + domain); } console.log("----------"); }); } }); ``` ### Response #### Success Response (200) - **code** (number) - Response code. - **time** (Array) - Timestamp for each data point. - **data** (Object) - An object containing bandwidth data for each domain. - **[domainName]** (Object) - Bandwidth data for a specific domain. - **china** (Array) - Bandwidth data for China region. - **oversea** (Array) - Bandwidth data for overseas regions. #### Response Example ```json { "code": 0, "time": [1497945600, 1498032000, 1498118400], "data": { "if-pbl.qiniudn.com": { "china": [100, 120, 110], "oversea": [50, 60, 55] }, "qdisk.qiniudn.com": { "china": [200, 230, 210], "oversea": [100, 130, 110] } } } ``` ``` -------------------------------- ### Get Image EXIF Data via Cloud Processing Source: https://github.com/qiniu/nodejs-sdk/wiki/Home Generates a URL to retrieve EXIF metadata from an image using Qiniu's cloud processing. Requires a base image URL and applies the `Exif` fop. ```javascript var exif = new qiniu.fop.Exif(); url = exif.makeRequest(url); ``` -------------------------------- ### Get Image Information via Cloud Processing Source: https://github.com/qiniu/nodejs-sdk/wiki/Home Generates a URL to retrieve image information (format, dimensions, size) using Qiniu's cloud processing. Requires a base image URL and applies the `ImageInfo` fop. ```javascript var ii = new qiniu.fop.ImageInfo(); url = ii.makeRequest(url); ``` -------------------------------- ### Initialization and Authentication - Mac / conf.Config Source: https://context7.com/qiniu/nodejs-sdk/llms.txt Demonstrates how to initialize the Mac object with AccessKey and SecretKey for authentication, and the Config object for global runtime parameters like HTTPS usage and upload acceleration. ```APIDOC ## Initialization and Authentication - `Mac` / `conf.Config` `Mac` object holds AccessKey and SecretKey, serving as the identity credential for all API calls; `Config` object configures global runtime parameters such as whether to use HTTPS, enable upload acceleration, and specify custom regions. ```javascript const qiniu = require('qiniu'); // Initialize authentication object const accessKey = process.env.QINIU_ACCESS_KEY; const secretKey = process.env.QINIU_SECRET_KEY; const mac = new qiniu.auth.digest.Mac(accessKey, secretKey); // Configuration object: Use East China region, enable HTTPS const config = new qiniu.conf.Config({ useHttpsDomain: true, accelerateUploading: false, // Specify fixed region by region ID (optional, defaults to automatic query) regionsProvider: qiniu.httpc.Region.fromRegionId('z0') }); // Global configuration (compatible with older versions) qiniu.conf.ACCESS_KEY = accessKey; qiniu.conf.SECRET_KEY = secretKey; ``` ``` -------------------------------- ### 获取域名流量 (Get Domain Traffic Data) Source: https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md Retrieves traffic data for specified domains within a given date range and granularity. ```APIDOC ## 获取域名流量 (Get Domain Traffic Data) ### Description Retrieves traffic data for specified domains within a given date range and granularity. ### Method `cdnManager.getFluxData(startDate, endDate, granularity, domains, callback)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **startDate** (string) - Required - The start date for the data retrieval (YYYY-MM-DD). - **endDate** (string) - Required - The end date for the data retrieval (YYYY-MM-DD). - **granularity** (string) - Required - The granularity of the data ('day', 'hour'). - **domains** (Array) - Required - A list of domain names to retrieve data for. - **callback** (Function) - Required - A callback function that handles the response. - **err**: Error object if an error occurred. - **respBody**: The response body from the server. - **respInfo**: Information about the response, including status code. ### Request Example ```javascript //域名列表 var domains = [ 'if-pbl.qiniudn.com', 'qdisk.qiniudn.com' ]; //指定日期 var startDate = '2017-06-20'; var endDate = '2017-06-22'; var granularity = 'day'; //获取域名流量 cdnManager.getFluxData(startDate, endDate, granularity, domains, function(err, respBody, respInfo) { if (err) { throw err; } console.log(respInfo.statusCode); if (respInfo.statusCode == 200) { var jsonBody = JSON.parse(respBody); var code = jsonBody.code; console.log(code); var tickTime = jsonBody.time; console.log(tickTime); var fluxData = jsonBody.data; domains.forEach(function(domain) { var fluxDataOfDomain = fluxData[domain]; if (fluxDataOfDomain != null) { console.log("flux data for:" + domain); var fluxChina = fluxDataOfDomain["china"]; var fluxOversea = fluxDataOfDomain["oversea"]; console.log(fluxChina); console.log(fluxOversea); } else { console.log("no flux data for:" + domain); } console.log("----------"); }); } }); ``` ### Response #### Success Response (200) - **code** (number) - Response code. - **time** (Array) - Timestamp for each data point. - **data** (Object) - An object containing traffic data for each domain. - **[domainName]** (Object) - Traffic data for a specific domain. - **china** (Array) - Traffic data for China region. - **oversea** (Array) - Traffic data for overseas regions. #### Response Example ```json { "code": 0, "time": [1497945600, 1498032000, 1498118400], "data": { "if-pbl.qiniudn.com": { "china": [102400, 123456, 112233], "oversea": [51200, 67890, 55443] }, "qdisk.qiniudn.com": { "china": [204800, 234567, 212345], "oversea": [102400, 134567, 111234] } } } ``` ``` -------------------------------- ### Initialize SDK Environment Source: https://github.com/qiniu/nodejs-sdk/wiki/Home Set your AccessKey and SecretKey before using the SDK for server-side operations. These are required for signature authorization. ```javascript qiniu.conf.ACCESS_KEY = '' qiniu.conf.SECRET_KEY = '' ``` -------------------------------- ### Get File Information Source: https://github.com/qiniu/nodejs-sdk/wiki/Home Retrieves metadata for a specific file in a bucket. This includes hash, file size, upload time, and MIME type. ```APIDOC ## Get File Information ### Description Retrieves metadata for a specific file in a bucket. ### Method `client.stat(bucketName, key, callback)` ### Parameters - **bucketName** (string) - The name of the bucket. - **key** (string) - The key of the file. - **callback** (function) - A function to handle the response or error. ### Request Example ```javascript var client = new qiniu.rs.Client(); client.stat(bucketName, key, function(err, ret) { if (!err) { // ok // ret has keys (hash, fsize, putTime, mimeType) } else { console.log(err); } }); ``` ### Response #### Success Response - **hash** (string) - The hash of the file. - **fsize** (number) - The size of the file in bytes. - **putTime** (number) - The upload time of the file. - **mimeType** (string) - The MIME type of the file. ``` -------------------------------- ### Initialize Authentication and Configuration Source: https://context7.com/qiniu/nodejs-sdk/llms.txt Initialize the Mac object with AccessKey and SecretKey for authentication. Configure global runtime parameters like HTTPS usage and upload acceleration with the Config object. ```javascript const qiniu = require('qiniu'); // 初始化鉴权对象 const accessKey = process.env.QINIU_ACCESS_KEY; const secretKey = process.env.QINIU_SECRET_KEY; const mac = new qiniu.auth.digest.Mac(accessKey, secretKey); // 配置对象:使用华东区域、启用 HTTPS const config = new qiniu.conf.Config({ useHttpsDomain: true, accelerateUploading: false, // 通过区域 ID 指定固定区域(可选,默认自动查询) regionsProvider: qiniu.httpc.Region.fromRegionId('z0') }); // 全局方式(兼容旧版) qiniu.conf.ACCESS_KEY = accessKey; qiniu.conf.SECRET_KEY = secretKey; ``` -------------------------------- ### Batch Get File Information Source: https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md Perform a batch of stat operations to retrieve metadata for multiple files simultaneously. Each batch request is limited to 1000 operations. ```javascript //每个operations的数量不可以超过1000个,如果总数量超过1000,需要分批发送 const statOperations = [ qiniu.rs.statOp(srcBucket, 'qiniu1.mp4'), qiniu.rs.statOp(srcBucket, 'qiniu2.mp4'), qiniu.rs.statOp(srcBucket, 'qiniu3.mp4'), qiniu.rs.statOp(srcBucket, 'qiniu4x.mp4'), ]; bucketManager.batch(statOperations) .then(({ data, resp }) => { // 200 is success, 298 is part success if (Math.floor(respInfo.statusCode / 100) === 2) { respBody.forEach(function(item) { console.log(item.data.fsize); console.log(item.data.hash); console.log(item.data.mimeType); console.log(item.data.putTime); console.log(item.data.type); }); } else { console.log(resp.statusCode); console.log(data); } }) .catch(err => { console.log('failed', err); }); ``` -------------------------------- ### Initialize Qiniu SDK Configuration Source: https://github.com/qiniu/nodejs-sdk/wiki/Home Initializes the Qiniu SDK with your Access Key and Secret Key. This is a prerequisite for performing server-side resource operations. ```javascript qiniu.conf.ACCESS_KEY = ''; qiniu.conf.SECRET_KEY = ''; ``` -------------------------------- ### Initialize BucketManager Source: https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md Instantiate a BucketManager object to perform resource management operations. Requires authentication credentials and configuration. ```javascript 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); ``` -------------------------------- ### Get File Information Source: https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md Retrieve metadata for a file in a specified bucket. Handles successful responses by logging file details and errors by logging status codes and data. ```javascript const bucket = "if-pbl"; const key = "qiniux.mp4"; bucketManager.stat(bucket, key) .then(({ data, resp }) => { if (resp.statusCode === 200) { console.log(data.hash); console.log(data.fsize); console.log(data.mimeType); console.log(data.putTime); console.log(data.type); } else { console.log(resp.statusCode); console.log(data); } }) .catch(err => { console.log('failed', err); }); ``` -------------------------------- ### List Files with BucketManager.listPrefix Source: https://context7.com/qiniu/nodejs-sdk/llms.txt Enumerate files within a bucket based on a prefix, supporting pagination with `marker` and directory separation with `delimiter`. Each call returns a maximum of 1000 records. ```APIDOC ## 文件列表查询 — `BucketManager.listPrefix` 按前缀枚举空间内的文件列表,支持分页(marker)和目录分隔符(delimiter),每次最多返回 1000 条记录。 ```javascript const qiniu = require('qiniu'); const mac = new qiniu.auth.digest.Mac(process.env.QINIU_ACCESS_KEY, process.env.QINIU_SECRET_KEY); const bucketManager = new qiniu.rs.BucketManager(mac, new qiniu.conf.Config()); // 按前缀列举文件,使用 '/' 作目录分隔符 async function listAllFiles (bucket, prefix) { let marker = ''; const allFiles = []; do { const { data, resp } = await bucketManager.listPrefix(bucket, { prefix, limit: 1000, delimiter: '/', marker }); if (resp.statusCode !== 200) { throw new Error(`列举失败: ${resp.statusCode}`); } (data.items || []).forEach(item => { allFiles.push(item); console.log(`文件: ${item.key} 大小: ${item.fsize} MIME: ${item.mimeType}`); }); // commonPrefixes 包含"子目录"列表 (data.commonPrefixes || []).forEach(dir => console.log('目录:', dir)); marker = data.marker || ''; } while (marker); return allFiles; } listAllFiles('my-bucket', 'images/') .then(files => console.log(`共找到 ${files.length} 个文件`)) .catch(err => console.error(err)); ``` ``` -------------------------------- ### Get File Information Source: https://github.com/qiniu/nodejs-sdk/wiki/Home Retrieves metadata for a file in a specified bucket. The returned data includes hash, fsize, putTime, and mimeType. Handles potential errors during the operation. ```javascript var client = new qiniu.rs.Client(); client.stat(bucketName, key, function(err, ret) { if (!err) { // ok // ret has keys (hash, fsize, putTime, mimeType) } else { console.log(err); // http://developer.qiniu.com/docs/v6/api/reference/codes.html } }); ``` -------------------------------- ### Copy File Source: https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md Create a copy of a file in the same or a different bucket. The `options` object can include `force: true` to overwrite existing files. The original file remains after copying. ```javascript const srcBucket = "if-pbl"; const srcKey = "qiniu.mp4"; const destBucket = "if-pbl"; const destKey = "qiniu_new_copy.mp4"; // 强制覆盖已有同名文件 const options = { force: true } bucketManager.copy(srcBucket, srcKey, destBucket, destKey, options) .then(({ data, resp }) => { if (resp.statusCode === 200) { console.log(data); } else { console.log(resp.statusCode); console.log(data); } }) .catch(err => { console.log('failed', err); }); ``` -------------------------------- ### Batch Get File Information Source: https://github.com/qiniu/nodejs-sdk/wiki/Home Retrieves metadata for multiple files in a batch request. It's important to check the 'code' for each item in the response, as individual operations within the batch might succeed or fail. ```javascript var path0 = new qiniu.rs.EntryPath(bucketName, key0); var path1 = new qiniu.rs.EntryPath(bucketName, key1); var path2 = new qiniu.rs.EntryPath(bucketName, key2); var client = new qiniu.rs.Client(); client.batchStat([path0, path1, path2], function(err, ret) { if (!err) { for (i in ret) { if (ret[i].code === 200) { //ok, ret[i].data has keys (hash, fsize, putTime, mimeType) } else { // parse error code console.log(ret[i].code, ret[i].data); // http://developer.qiniu.com/docs/v6/api/reference/codes.html } } } else { console.log(err); // http://developer.qiniu.com/docs/v6/api/reference/codes.html } }); ``` -------------------------------- ### List Files by Prefix with BucketManager.listPrefix Source: https://context7.com/qiniu/nodejs-sdk/llms.txt Enumerate files within a bucket by prefix, supporting pagination with `marker` and directory separation using `delimiter`. Returns up to 1000 records per request. ```javascript const qiniu = require('qiniu'); const mac = new qiniu.auth.digest.Mac(process.env.QINIU_ACCESS_KEY, process.env.QINIU_SECRET_KEY); const bucketManager = new qiniu.rs.BucketManager(mac, new qiniu.conf.Config()); // 按前缀列举文件,使用 '/' 作目录分隔符 async function listAllFiles (bucket, prefix) { let marker = ''; const allFiles = []; do { const { data, resp } = await bucketManager.listPrefix(bucket, { prefix, limit: 1000, delimiter: '/', marker }); if (resp.statusCode !== 200) { throw new Error(`列举失败: ${resp.statusCode}`); } (data.items || []).forEach(item => { allFiles.push(item); console.log(`文件: ${item.key} 大小: ${item.fsize} MIME: ${item.mimeType}`); }); // commonPrefixes 包含"子目录"列表 (data.commonPrefixes || []).forEach(dir => console.log('目录:', dir)); marker = data.marker || ''; } while (marker); return allFiles; } listAllFiles('my-bucket', 'images/') .then(files => console.log(`共找到 ${files.length} 个文件`)) .catch(err => console.error(err)); ``` -------------------------------- ### List Files in Bucket with Prefix Filter Source: https://github.com/qiniu/nodejs-sdk/wiki/Home Use `rsf.listPrefix` to list files in a bucket, optionally filtering by a prefix. Initialize marker to null for the first call and use the returned marker for subsequent calls to paginate through results. ```javascript qiniu.conf.ACCESS_KEY = ''; qiniu.conf.SECRET_KEY = ''; qiniu.rsf.listPrefix(bucketname, prefix, marker, limit, function(err, ret) { if (!err) { // process ret.marker & ret.items } else { console.log(err) // http://developer.qiniu.com/docs/v6/api/reference/rs/list.html } }); ``` -------------------------------- ### Get Domain Traffic Data with Node.js SDK Source: https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md Retrieve traffic data for specified domains within a date range and granularity. The code iterates through domains to display China and overseas traffic, handling cases where data might be missing. ```javascript //域名列表 var domains = [ 'if-pbl.qiniudn.com', 'qdisk.qiniudn.com' ]; //指定日期 var startDate = '2017-06-20'; var endDate = '2017-06-22'; var granularity = 'day'; //获取域名流量 cdnManager.getFluxData(startDate, endDate, granularity, domains, function(err, respBody, respInfo) { if (err) { throw err; } console.log(respInfo.statusCode); if (respInfo.statusCode == 200) { var jsonBody = JSON.parse(respBody); var code = jsonBody.code; console.log(code); var tickTime = jsonBody.time; console.log(tickTime); var fluxData = jsonBody.data; domains.forEach(function(domain) { var fluxDataOfDomain = fluxData[domain]; if (fluxDataOfDomain != null) { console.log("flux data for:" + domain); var fluxChina = fluxDataOfDomain["china"]; var fluxOversea = fluxDataOfDomain["oversea"]; console.log(fluxChina); console.log(fluxOversea); } else { console.log("no flux data for:" + domain); } console.log("----------"); }); } }); ``` -------------------------------- ### Fetch Network Resource to Bucket Source: https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md Download a file from a given URL and upload it to your Qiniu bucket. Useful for importing external content. ```javascript const resUrl = 'http://devtools.qiniu.com/qiniu.png'; const bucket = "if-bc"; const key = "qiniu.png"; bucketManager.fetch(resUrl, bucket, key) .then(({ data, resp }) => { if (resp.statusCode === 200) { console.log(respBody.key); console.log(respBody.hash); console.log(respBody.fsize); console.log(respBody.mimeType); } else { console.log(resp.statusCode); console.log(data); } }) .catch(err => { console.log('failed', err); }); ``` -------------------------------- ### Initialize Authentication Object Source: https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md Create an authentication object using your Access Key and Secret Key. This object is required for all SDK operations that need authorization. ```javascript const accessKey = 'your access key'; const secretKey = 'your secret key'; const mac = new qiniu.auth.digest.Mac(accessKey, secretKey); ``` -------------------------------- ### Get Domain Bandwidth Data with Node.js SDK Source: https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md Fetch bandwidth data for specified domains within a date range and granularity. The code processes the response to display China and overseas bandwidth, including checks for missing data per domain. ```javascript //域名列表 var domains = [ 'if-pbl.qiniudn.com', 'qdisk.qiniudn.com' ]; //指定日期 var startDate = '2017-06-20'; var endDate = '2017-06-22'; var granularity = 'day'; //获取域名带宽 cdnManager.getBandwidthData(startDate, endDate, granularity, domains, function( err, respBody, respInfo) { if (err) { console.log(err); throw err; } console.log(respInfo.statusCode); if (respInfo.statusCode == 200) { var jsonBody = JSON.parse(respBody); var code = jsonBody.code; console.log(code); var tickTime = jsonBody.time; console.log(tickTime); var bandwidthData = jsonBody.data; domains.forEach(function(domain) { var bandwidthDataOfDomain = bandwidthData[domain]; if (bandwidthDataOfDomain != null) { console.log("bandwidth data for:" + domain); var bandwidthChina = bandwidthDataOfDomain["china"]; var bandwidthOversea = bandwidthDataOfDomain["oversea"]; console.log(bandwidthChina); console.log(bandwidthOversea); } else { console.log("no bandwidth data for:" + domain); } console.log("----------"); }); } }); ``` -------------------------------- ### List Files with Prefix Source: https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md Retrieves a list of files in a bucket that match a specified prefix, with options for pagination and filtering. ```APIDOC ## List Files with Prefix ### Description Retrieves a list of files in a bucket that match a specified prefix. Supports options for limiting results, setting markers for pagination, and specifying a delimiter for directory-like listing. ### Method `bucketManager.listPrefix(bucket, options)` ### Parameters - **bucket** (string) - The name of the bucket. - **options** (object) - Optional parameters for listing: - **limit** (number) - Maximum number of items to return per request. - **prefix** (string) - Filters results to files with this prefix. - **marker** (string) - A marker for pagination, indicating the starting point for the next list. - **delimiter** (string) - A delimiter to group items, useful for simulating directory structures. ### Request Example ```javascript const bucket = 'if-pbl'; const options = { limit: 10, prefix: 'images/', }; let nextMarker = ''; bucketManager.listPrefix(bucket, options) .then(({ data, resp }) => { if (resp.statusCode === 200) { const commonPrefixes = data.commonPrefixes; nextMarker = data.marker console.log(nextMarker); console.log(commonPrefixes); const items = data.items; items.forEach(function(item) { console.log(item.key); }); } else { console.log(resp.statusCode); console.log(data); } }) .catch(err => { console.log('failed', err); }); ``` ``` -------------------------------- ### File Resource Management with BucketManager Source: https://context7.com/qiniu/nodejs-sdk/llms.txt Provides comprehensive file management capabilities within a Qiniu storage bucket, including querying, copying, moving, deleting, modifying attributes, and generating download links. ```APIDOC ## 文件资源管理 — `BucketManager` `BucketManager` 提供对七牛云存储空间内文件的完整管理能力,包括查询、复制、移动、删除、修改属性、生成下载链接等操作,所有方法均返回 Promise 且同时支持回调函数。 ```javascript const qiniu = require('qiniu'); const mac = new qiniu.auth.digest.Mac(process.env.QINIU_ACCESS_KEY, process.env.QINIU_SECRET_KEY); const config = new qiniu.conf.Config(); const bucketManager = new qiniu.rs.BucketManager(mac, config); const bucket = 'my-bucket'; // 1. 查询文件信息 bucketManager.stat(bucket, 'video.mp4') .then(({ data, resp }) => { if (resp.statusCode === 200) { console.log('哈希:', data.hash); console.log('文件大小:', data.fsize, '字节'); console.log('MIME 类型:', data.mimeType); console.log('上传时间:', data.putTime); // 输出: 哈希: Fn8x... 文件大小: 10485760 字节 MIME 类型: video/mp4 } }); // 2. 复制文件 bucketManager.copy(bucket, 'video.mp4', bucket, 'video-backup.mp4', { force: true }) .then(({ resp }) => console.log('复制结果:', resp.statusCode)); // 3. 移动/重命名文件 bucketManager.move(bucket, 'old-name.jpg', bucket, 'new-name.jpg', { force: false }) .then(({ resp }) => console.log('移动结果:', resp.statusCode)); // 4. 删除文件 bucketManager.delete(bucket, 'temp-file.txt') .then(({ resp }) => console.log('删除结果:', resp.statusCode)); // 5. 修改文件 MIME 类型 bucketManager.changeMime(bucket, 'data.bin', 'application/octet-stream') .then(({ resp }) => console.log('修改 MIME 结果:', resp.statusCode)); // 6. 修改文件存储类型(0: 标准, 1: 低频, 2: 归档, 3: 深度归档) bucketManager.changeType(bucket, 'archive.zip', 2) .then(({ resp }) => console.log('修改存储类型结果:', resp.statusCode)); // 7. 设置文件过期删除(N 天后自动删除) bucketManager.deleteAfterDays(bucket, 'tmp-log.txt', 30) .then(({ resp }) => console.log('设置删除周期结果:', resp.statusCode)); // 8. 生成公开下载链接 const publicUrl = bucketManager.publicDownloadUrl('http://cdn.example.com', 'images/pic.jpg'); console.log('公开链接:', publicUrl); // 输出: 公开链接: http://cdn.example.com/images/pic.jpg // 9. 生成私有下载链接(1 小时有效) const deadline = Math.floor(Date.now() / 1000) + 3600; const privateUrl = bucketManager.privateDownloadUrl('http://priv.example.com', 'secret.pdf', deadline); console.log('私有链接:', privateUrl); // 输出: http://priv.example.com/secret.pdf?e=1700000000&token=AK:sign... ``` ``` -------------------------------- ### Configure Uploader Settings Source: https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md Build a configuration object for uploaders, specifying the region for the bucket and other upload-related parameters like HTTPS usage and CDN acceleration. ```javascript const config = new qiniu.conf.Config(); // 空间对应的机房 config.regionsProvider = qiniu.httpc.Region.fromRegionId('z0'); // Zone 对象已弃用,目前暂时兼容。regionsProvider 配置项优先级更高。 // config.zone = qiniu.zone.Zone_z0; // 是否使用https域名 //config.useHttpsDomain = true; // 上传是否使用cdn加速 //config.useCdnDomain = true; ``` -------------------------------- ### List Files with Specified Prefix Source: https://github.com/qiniu/nodejs-sdk/blob/master/docs/nodejs-sdk-v7.md Retrieve a list of files within a bucket that match a given prefix. Supports pagination and directory-like listing using delimiters. ```javascript const bucket = 'if-pbl'; // @param options 列举操作的可选参数 // prefix 列举的文件前缀 // marker 上一次列举返回的位置标记,作为本次列举的起点信息 // limit 每次返回的最大列举文件数量 // delimiter 指定目录分隔符 const options = { limit: 10, prefix: 'images/', }; let nextMarker = ''; bucketManager.listPrefix(bucket, options) .then(({ data, resp }) => { if (resp.statusCode === 200) { //如果这个nextMarker不为空,那么还有未列举完毕的文件列表,下次调用listPrefix的时候, //指定options里面的marker为这个值 const commonPrefixes = data.commonPrefixes; nextMarker = data.marker console.log(nextMarker); console.log(commonPrefixes); const items = data.items; items.forEach(function(item) { console.log(item.key); // console.log(item.putTime); // console.log(item.hash); // console.log(item.fsize); // console.log(item.mimeType); // console.log(item.endUser); // console.log(item.type); }); } else { console.log(resp.statusCode); console.log(data); } }) .catch(err => { console.log('failed', err); }); ``` -------------------------------- ### Qiniu Utility Functions for Signing and Encoding Source: https://context7.com/qiniu/nodejs-sdk/llms.txt Provides utility functions for generating QBox and Qiniu V2 signatures, validating Qiniu upload callbacks, and performing URL-safe Base64 encoding/decoding. Requires Qiniu credentials. ```javascript const qiniu = require('qiniu'); const mac = new qiniu.auth.digest.Mac(process.env.QINIU_ACCESS_KEY, process.env.QINIU_SECRET_KEY); // 1. 生成 QBox 管理凭证(用于自定义 API 请求) const accessToken = qiniu.util.generateAccessToken( mac, 'http://rs.qiniu.com/stat/' + qiniu.util.encodedEntry('my-bucket', 'test.mp4'), '' ); console.log('QBox Token:', accessToken); // 2. 生成 Qiniu V2 签名(用于新版管理 API) const tokenV2 = qiniu.util.generateAccessTokenV2( mac, 'https://rs.qiniuapi.com/stat/' + qiniu.util.encodedEntry('my-bucket', 'test.mp4'), 'GET', 'application/x-www-form-urlencoded', '', {} ); console.log('Qiniu V2 Token:', tokenV2); // 3. 校验七牛上传回调合法性 const isValid = qiniu.util.isQiniuCallback( mac, 'https://api.example.com/qiniu/callback', '{"key":"test.mp4","hash":"Fn8x..."}', req.headers['authorization'], // 来自七牛回调请求的 Authorization { reqMethod: 'POST', reqContentType: 'application/json' } ); console.log('回调合法性:', isValid); // true / false // 4. URL 安全 Base64 编码/解码 const encoded = qiniu.util.urlsafeBase64Encode('my-bucket:test.mp4'); console.log('编码结果:', encoded); const decoded = qiniu.util.urlSafeBase64Decode(encoded); console.log('解码结果:', decoded); // my-bucket:test.mp4 // 5. 编码 Entry(用于 RS 类 API 路径) const entry = qiniu.util.encodedEntry('my-bucket', 'dir/file.txt'); console.log('encodedEntry:', entry); ``` -------------------------------- ### Fetch Remote Resources with BucketManager.fetch Source: https://context7.com/qiniu/nodejs-sdk/llms.txt Directly fetch files from a given HTTP/HTTPS URL and save them to your Qiniu cloud storage. This method bypasses your business server, making it ideal for migrating external resources. Ensure the remote URL is accessible and the bucket exists. ```javascript const qiniu = require('qiniu'); const mac = new qiniu.auth.digest.Mac(process.env.QINIU_ACCESS_KEY, process.env.QINIU_SECRET_KEY); const bucketManager = new qiniu.rs.BucketManager(mac, new qiniu.conf.Config()); const remoteUrl = 'https://www.qiniu.com/qiniu.png'; const bucket = 'my-bucket'; const saveKey = 'fetched/qiniu-logo.png'; bucketManager.fetch(remoteUrl, bucket, saveKey) .then(({ data, resp }) => { if (resp.statusCode === 200) { console.log('抓取成功'); console.log('Key:', data.key); console.log('Hash:', data.hash); console.log('MimeType:', data.mimeType); console.log('Fsize:', data.fsize); } else { console.error('抓取失败:', resp.statusCode, data); } }) .catch(err => console.error('请求异常:', err)); ``` -------------------------------- ### Resumable Upload with ResumeUploader Source: https://context7.com/qiniu/nodejs-sdk/llms.txt Demonstrates how to upload large files using the `ResumeUploader` class, which supports resumable uploads and chunked transfer protocols (v1 and v2). ```APIDOC ## 分片断点续传 — `ResumeUploader` `ResumeUploader` 将大文件切分为多个分片分批上传,支持断点续传(通过 `resumeRecordFile` 或 `resumeRecorder` 记录进度),支持 v1 和 v2 两种分片协议(默认 v2)。 ```javascript const qiniu = require('qiniu'); const mac = new qiniu.auth.digest.Mac(process.env.QINIU_ACCESS_KEY, process.env.QINIU_SECRET_KEY); const config = new qiniu.conf.Config({ useHttpsDomain: false }); const resumeUploader = new qiniu.resume_up.ResumeUploader(config); const uploadToken = new qiniu.rs.PutPolicy({ scope: 'my-bucket' }).uploadToken(mac); // 配置分片上传参数 const putExtra = qiniu.resume_up.PutExtra.create( 'video.mp4', // fname { 'x:type': 'video' }, // 自定义变量 'video/mp4', // mimeType 'progress.log', // resumeRecordFile(断点记录文件) function (uploadBytes, totalBytes) { const pct = (uploadBytes / totalBytes * 100).toFixed(1); console.log(`上传进度: ${pct}% (${uploadBytes}/${totalBytes})`); }, 4 * 1024 * 1024, // partSize: 4MB 'v2' // 使用分片 v2 协议 ); // 分片上传本地大文件(v2 协议) resumeUploader.putFileV2(uploadToken, 'videos/movie.mp4', '/tmp/large-video.mp4', putExtra) .then(({ data, resp }) => { if (resp.statusCode === 200) { console.log('上传成功:', data); // 输出: 上传成功: { hash: 'Fn...', key: 'videos/movie.mp4' } } else { console.error('上传失败:', resp.statusCode, data); } }) .catch(err => console.error('上传异常:', err)); ``` ``` -------------------------------- ### Bucket File Management with BucketManager Source: https://context7.com/qiniu/nodejs-sdk/llms.txt Perform various file operations in a Qiniu bucket using `BucketManager`. Supports querying file stats, copying, moving, deleting, changing MIME types, storage types, and setting auto-delete timers. ```javascript const qiniu = require('qiniu'); const mac = new qiniu.auth.digest.Mac(process.env.QINIU_ACCESS_KEY, process.env.QINIU_SECRET_KEY); const config = new qiniu.conf.Config(); const bucketManager = new qiniu.rs.BucketManager(mac, config); const bucket = 'my-bucket'; // 1. 查询文件信息 bucketManager.stat(bucket, 'video.mp4') .then(({ data, resp }) => { if (resp.statusCode === 200) { console.log('哈希:', data.hash); console.log('文件大小:', data.fsize, '字节'); console.log('MIME 类型:', data.mimeType); console.log('上传时间:', data.putTime); // 输出: 哈希: Fn8x... 文件大小: 10485760 字节 MIME 类型: video/mp4 } }); // 2. 复制文件 bucketManager.copy(bucket, 'video.mp4', bucket, 'video-backup.mp4', { force: true }) .then(({ resp }) => console.log('复制结果:', resp.statusCode)); // 3. 移动/重命名文件 bucketManager.move(bucket, 'old-name.jpg', bucket, 'new-name.jpg', { force: false }) .then(({ resp }) => console.log('移动结果:', resp.statusCode)); // 4. 删除文件 bucketManager.delete(bucket, 'temp-file.txt') .then(({ resp }) => console.log('删除结果:', resp.statusCode)); // 5. 修改文件 MIME 类型 bucketManager.changeMime(bucket, 'data.bin', 'application/octet-stream') .then(({ resp }) => console.log('修改 MIME 结果:', resp.statusCode)); // 6. 修改文件存储类型(0: 标准, 1: 低频, 2: 归档, 3: 深度归档) bucketManager.changeType(bucket, 'archive.zip', 2) .then(({ resp }) => console.log('修改存储类型结果:', resp.statusCode)); // 7. 设置文件过期删除(N 天后自动删除) bucketManager.deleteAfterDays(bucket, 'tmp-log.txt', 30) .then(({ resp }) => console.log('设置删除周期结果:', resp.statusCode)); // 8. 生成公开下载链接 const publicUrl = bucketManager.publicDownloadUrl('http://cdn.example.com', 'images/pic.jpg'); console.log('公开链接:', publicUrl); // 输出: 公开链接: http://cdn.example.com/images/pic.jpg // 9. 生成私有下载链接(1 小时有效) const deadline = Math.floor(Date.now() / 1000) + 3600; const privateUrl = bucketManager.privateDownloadUrl('http://priv.example.com', 'secret.pdf', deadline); console.log('私有链接:', privateUrl); // 输出: http://priv.example.com/secret.pdf?e=1700000000&token=AK:sign... ``` -------------------------------- ### Manage Buckets with BucketManager (Bucket Level) Source: https://context7.com/qiniu/nodejs-sdk/llms.txt Provides bucket-level management functions including listing all buckets, creating new buckets with specified regions, retrieving bucket information, setting anti-leech rules (whitelist/blacklist), configuring CORS, and setting storage quotas. Each operation requires proper authentication and may have specific parameters. ```javascript const qiniu = require('qiniu'); const mac = new qiniu.auth.digest.Mac(process.env.QINIU_ACCESS_KEY, process.env.QINIU_SECRET_KEY); const bucketManager = new qiniu.rs.BucketManager(mac, new qiniu.conf.Config()); // 1. 列举所有空间 bucketManager.listBucket() .then(({ data, resp }) => { if (resp.statusCode === 200) { console.log('空间列表:', data); // ['bucket1', 'bucket2', ...] } }); // 2. 创建空间(指定区域) bucketManager.createBucket('new-bucket', { regionId: 'z1' }) .then(({ resp }) => console.log('创建结果:', resp.statusCode)); // 3. 获取空间信息 bucketManager.getBucketInfo('my-bucket') .then(({ data, resp }) => { if (resp.statusCode === 200) console.log('空间信息:', data); }); // 4. 设置防盗链(白名单模式) bucketManager.putReferAntiLeech('my-bucket', { mode: 1, // 1: 白名单, 2: 黑名单, 0: 关闭 norefer: 1, // 1: 允许空 Referer 访问 pattern: '*.example.com;example.com', source_enabled: 0 // 0: 仅 CDN, 1: 源站也开启 }) .then(({ resp }) => console.log('防盗链设置结果:', resp.statusCode)); // 5. 设置 CORS 规则 bucketManager.putCorsRules('my-bucket', [ { allowed_origin: ['https://example.com'], allowed_method: ['GET', 'POST', 'PUT'], allowed_header: ['Content-Type', 'Authorization'], max_age: 3600 } ]) .then(({ resp }) => console.log('CORS 设置结果:', resp.statusCode)); // 6. 设置存储配额(最大 100GB,最多 100万 文件) bucketManager.putBucketQuota('my-bucket', { size: 100 * 1024 * 1024 * 1024, // 100 GB(字节) count: 1000000 }) .then(({ resp }) => console.log('配额设置结果:', resp.statusCode)); ```