付智勇

添加发送短信

正在显示 47 个修改的文件 包含 3976 行增加4 行删除
node_modules
example
.DS_Store
coverage
.nyc_output
output
\ No newline at end of file
... ...
'use strict';
const { RPCClient } = require('@alicloud/pop-core');
function hasOwnProperty(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
class Client extends RPCClient {
constructor(config) {
config.apiVersion = '2017-05-25';
super(config);
}
queryTokenForMnsQueue(params = {}, options) {
if (!hasOwnProperty(params, 'MessageType')) {
throw new TypeError('parameter "MessageType" is required');
}
return this.request('QueryTokenForMnsQueue', params, options);
}
}
module.exports = Client;
... ...
{
"_args": [
[
{
"raw": "@alicloud/dybaseapi@^1.0.0",
"scope": "@alicloud",
"escapedName": "@alicloud%2fdybaseapi",
"name": "@alicloud/dybaseapi",
"rawSpec": "^1.0.0",
"spec": ">=1.0.0 <2.0.0",
"type": "range"
},
"/Users/fzy/project/koa2_Sequelize_project/node_modules/@alicloud/sms-sdk"
]
],
"_from": "@alicloud/dybaseapi@>=1.0.0 <2.0.0",
"_id": "@alicloud/dybaseapi@1.0.0",
"_inCache": true,
"_location": "/@alicloud/dybaseapi",
"_nodeVersion": "8.1.4",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/dybaseapi-1.0.0.tgz_1501232100324_0.6043512229807675"
},
"_npmUser": {
"name": "jacksontian",
"email": "shyvo1987@gmail.com"
},
"_npmVersion": "5.0.3",
"_phantomChildren": {},
"_requested": {
"raw": "@alicloud/dybaseapi@^1.0.0",
"scope": "@alicloud",
"escapedName": "@alicloud%2fdybaseapi",
"name": "@alicloud/dybaseapi",
"rawSpec": "^1.0.0",
"spec": ">=1.0.0 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/@alicloud/sms-sdk"
],
"_resolved": "https://registry.npmjs.org/@alicloud/dybaseapi/-/dybaseapi-1.0.0.tgz",
"_shasum": "552edd0990f90dbd69d40237cdfeffc366d0a1f5",
"_shrinkwrap": null,
"_spec": "@alicloud/dybaseapi@^1.0.0",
"_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/@alicloud/sms-sdk",
"author": {
"name": "Jackson Tian"
},
"dependencies": {
"@alicloud/pop-core": "^1.3.3"
},
"description": "Dybaseapi SDK",
"devDependencies": {},
"directories": {},
"dist": {
"integrity": "sha512-4KEDgqES7IL60T/TWGSkLQkN6BYeHEw8smnPgac2J2MTES5v1ieCWvbLSuUUWi5SAXi7cydKoD4HUOmX7xwM+A==",
"shasum": "552edd0990f90dbd69d40237cdfeffc366d0a1f5",
"tarball": "https://registry.npmjs.org/@alicloud/dybaseapi/-/dybaseapi-1.0.0.tgz"
},
"gitHead": "62285c0fb2fc5772b31812621a52bda85ad5d2ee",
"license": "MIT",
"main": "lib/client.js",
"maintainers": [
{
"name": "jacksontian",
"email": "shyvo1987@gmail.com"
}
],
"name": "@alicloud/dybaseapi",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"scripts": {},
"version": "1.0.0"
}
... ...
node_modules
example
.DS_Store
coverage
.nyc_output
output
\ No newline at end of file
... ...
'use strict';
const { RPCClient } = require('@alicloud/pop-core');
function hasOwnProperty(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
class Client extends RPCClient {
constructor(config) {
config.apiVersion = '2017-05-25';
super(config);
}
queryInterSmsIsoInfo(params = {}, options) {
return this.request('QueryInterSmsIsoInfo', params, options);
}
querySendDetails(params = {}, options) {
if (!hasOwnProperty(params, 'PhoneNumber')) {
throw new TypeError('parameter "PhoneNumber" is required');
}
if (!hasOwnProperty(params, 'SendDate')) {
throw new TypeError('parameter "SendDate" is required');
}
if (!hasOwnProperty(params, 'PageSize')) {
throw new TypeError('parameter "PageSize" is required');
}
if (!hasOwnProperty(params, 'CurrentPage')) {
throw new TypeError('parameter "CurrentPage" is required');
}
return this.request('QuerySendDetails', params, options);
}
sendInterSms(params = {}, options) {
if (!hasOwnProperty(params, 'CountryCode')) {
throw new TypeError('parameter "CountryCode" is required');
}
if (!hasOwnProperty(params, 'PhoneNumbers')) {
throw new TypeError('parameter "PhoneNumbers" is required');
}
if (!hasOwnProperty(params, 'SignName')) {
throw new TypeError('parameter "SignName" is required');
}
if (!hasOwnProperty(params, 'TemplateCode')) {
throw new TypeError('parameter "TemplateCode" is required');
}
return this.request('SendInterSms', params, options);
}
sendSms(params = {}, options) {
if (!hasOwnProperty(params, 'PhoneNumbers')) {
throw new TypeError('parameter "PhoneNumbers" is required');
}
if (!hasOwnProperty(params, 'SignName')) {
throw new TypeError('parameter "SignName" is required');
}
if (!hasOwnProperty(params, 'TemplateCode')) {
throw new TypeError('parameter "TemplateCode" is required');
}
return this.request('SendSms', params, options);
}
}
module.exports = Client;
... ...
{
"_args": [
[
{
"raw": "@alicloud/dysmsapi@^1.0.0",
"scope": "@alicloud",
"escapedName": "@alicloud%2fdysmsapi",
"name": "@alicloud/dysmsapi",
"rawSpec": "^1.0.0",
"spec": ">=1.0.0 <2.0.0",
"type": "range"
},
"/Users/fzy/project/koa2_Sequelize_project/node_modules/@alicloud/sms-sdk"
]
],
"_from": "@alicloud/dysmsapi@>=1.0.0 <2.0.0",
"_id": "@alicloud/dysmsapi@1.0.0",
"_inCache": true,
"_location": "/@alicloud/dysmsapi",
"_nodeVersion": "8.1.4",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/dysmsapi-1.0.0.tgz_1501232179304_0.009140280773863196"
},
"_npmUser": {
"name": "jacksontian",
"email": "shyvo1987@gmail.com"
},
"_npmVersion": "5.0.3",
"_phantomChildren": {},
"_requested": {
"raw": "@alicloud/dysmsapi@^1.0.0",
"scope": "@alicloud",
"escapedName": "@alicloud%2fdysmsapi",
"name": "@alicloud/dysmsapi",
"rawSpec": "^1.0.0",
"spec": ">=1.0.0 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/@alicloud/sms-sdk"
],
"_resolved": "https://registry.npmjs.org/@alicloud/dysmsapi/-/dysmsapi-1.0.0.tgz",
"_shasum": "712ddd7ecff5c063537a3c304867d2eae02ffc95",
"_shrinkwrap": null,
"_spec": "@alicloud/dysmsapi@^1.0.0",
"_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/@alicloud/sms-sdk",
"author": {
"name": "Jackson Tian"
},
"dependencies": {
"@alicloud/pop-core": "^1.3.3"
},
"description": "Dysmsapi SDK",
"devDependencies": {},
"directories": {},
"dist": {
"integrity": "sha512-EKfEk/1g1+1UflbPDTISGhl9Zm+cnaxN792gWsqSzgqNmYAZs8DdXhf9ZvnoexiHvftmrHhQyXZZNGkozKK28g==",
"shasum": "712ddd7ecff5c063537a3c304867d2eae02ffc95",
"tarball": "https://registry.npmjs.org/@alicloud/dysmsapi/-/dysmsapi-1.0.0.tgz"
},
"gitHead": "5afcc0844a738d5b0680dae9aea70baeb7e59523",
"license": "MIT",
"main": "lib/client.js",
"maintainers": [
{
"name": "jacksontian",
"email": "shyvo1987@gmail.com"
}
],
"name": "@alicloud/dysmsapi",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"scripts": {},
"version": "1.0.0"
}
... ...
MIT License
Copyright (c) 2017 Alibaba Cloud
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
... ...
# mns-nodejs-sdk
[![NPM version][npm-image]][npm-url]
[![build status][travis-image]][travis-url]
[![coverage][cov-image]][cov-url]
[npm-image]: https://img.shields.io/npm/v/@alicloud/mns.svg?style=flat-square
[npm-url]: https://npmjs.org/package/@alicloud/mns
[travis-image]: https://img.shields.io/travis/aliyun/mns-nodejs-sdk/master.svg?style=flat-square
[travis-url]: https://travis-ci.org/aliyun/mns-nodejs-sdk.svg?branch=master
[cov-image]: https://coveralls.io/repos/aliyun/mns-nodejs-sdk/badge.svg?branch=master&service=github
[cov-url]: https://coveralls.io/github/aliyun/mns-nodejs-sdk?branch=master
Documents: http://doxmate.cool/aliyun/mns-nodejs-sdk/api.html
> 该 SDK 并未完全实现所有文档所提及的功能,如果您想使用的功能并未实现,请提[issue](https://github.com/aliyun/mns-nodejs-sdk/issues/new)以增加优先级。
## Installation
```bash
npm install @alicloud/mns --save
```
## API Spec
See: https://help.aliyun.com/document_detail/27475.html
## Test
```sh
ACCOUNT_ID=<ACCOUNT_ID> ACCESS_KEY_ID=<ACCESS_KEY_ID> ACCESS_KEY_SECRET=<ACCESS_KEY_SECRET> make test
```
## Installation
You can install it via npm/cnpm/yarn.
```sh
$ npm install @alicloud/mns --save
```
## Usage
```js
const MNSClient = require('@alicloud/mns');
const accountid = '<account id>';
var client = new MNSClient(accountid, {
region: '<region>',
accessKeyId: '<access key id>',
accessKeySecret: '<access key secret>',
// optional & default
secure: false, // use https or http
internal: false, // use internal endpoint
 vpc: false // use vpc endpoint
});
(async function () {
let res;
// create queue
res = await client.createQueue('test-queue2');
console.log(res);
// list queue
res = await client.listQueue();
console.log(JSON.stringify(res, null, 2));
// create topic
res = await client.createTopic('test-topic');
console.log(res);
// get topic attributes
res = await client.getTopicAttributes('test-topic');
console.log(res);
// publish message
res = await client.publishMessage('<topic name>', {
MessageBody: 'content',
MessageAttributes: {
DirectSMS: JSON.stringify({
FreeSignName: '',
TemplateCode: '<template code>',
Type: '<type>',
Receiver: '<phone number>',
SmsParams: JSON.stringify({
code: '<code>',
product: '<product>'
})
})
}
});
console.log(res);
})().then((data) => {
console.log(data);
}, (err) => {
console.log(err.stack);
});
```
## License
The [MIT](LICENSE) License
... ...
'use strict';
module.exports = require('./lib/client');
... ...
'use strict';
const assert = require('assert');
const debug = require('debug')('mns:client');
const httpx = require('httpx');
const kitx = require('kitx');
const {
getEndpoint,
toXMLBuffer,
parseXML,
extract,
getResponseHeaders,
getCanonicalizedMNSHeaders
} = require('./helper');
class Client {
constructor(accountid, opts) {
assert(accountid, '"accountid" must be passed in');
this.accountid = accountid;
assert(opts, 'must pass in "opts"');
// 兼容
const accessKeyID = opts.accessKeyId || opts.accessKeyID;
assert(accessKeyID, 'must pass in "opts.accessKeyID"');
this.accessKeyID = accessKeyID;
assert(opts.accessKeySecret, 'must pass in "opts.accessKeySecret"');
this.accessKeySecret = opts.accessKeySecret;
assert(opts.region, 'must pass in "opts.region"');
const {domain, endpoint} = getEndpoint(accountid, opts);
this.endpointDomain = domain;
this.endpoint = endpoint;
// security token
this.securityToken = opts.securityToken;
}
async request(method, resource, type, requestBody, attentions = [], opts = {}) {
const url = `${this.endpoint}${resource}`;
debug('url: %s', url);
debug('method: %s', method);
const headers = this.buildHeaders(method, requestBody, resource, opts.headers);
debug('request headers: %j', headers);
debug('request body: %s', requestBody.toString());
const response = await httpx.request(url, Object.assign(opts, {
method: method,
headers: headers,
data: requestBody
}));
debug('statusCode %s', response.statusCode);
debug('response headers: %j', response.headers);
const code = response.statusCode;
const contentType = response.headers['content-type'] || '';
// const contentLength = response.headers['content-length'];
const responseBody = await httpx.read(response, 'utf8');
debug('response body: %s', responseBody);
var body;
if (responseBody && contentType.startsWith('text/xml')) {
const responseData = await parseXML(responseBody);
if (responseData.Error) {
const e = responseData.Error;
const message = extract(e.Message);
const requestid = extract(e.RequestId);
const hostid = extract(e.HostId);
const err = new Error(`${method} ${url} failed with ${code}. ` +
`requestid: ${requestid}, hostid: ${hostid}, message: ${message}`);
err.name = 'MNS' + extract(e.Code) + err.name;
throw err;
}
body = {};
Object.keys(responseData[type]).forEach((key) => {
if (key !== '$') {
body[key] = extract(responseData[type][key]);
}
});
}
return {
code,
headers: getResponseHeaders(response.headers, attentions),
body: body
};
}
get(resource, type, opts) {
return this.request('GET', resource, type, '', [], opts);
}
put(resource, type, body, attentions = [], opts = {}) {
return this.request('PUT', resource, type, body, attentions, opts);
}
post(resource, type, body) {
return this.request('POST', resource, type, body);
}
delete(resource) {
return this.request('DELETE', resource, undefined, '');
}
sign(verb, headers, resource) {
const canonicalizedMNSHeaders = getCanonicalizedMNSHeaders(headers);
const md5 = headers['content-md5'] || '';
const date = headers['date'];
const type = headers['content-type'] || '';
var toSignString = `${verb}\n${md5}\n${type}\n${date}\n${canonicalizedMNSHeaders}${resource}`;
// Signature = base64(hmac-sha1(VERB + "\n"
// + CONTENT-MD5 + "\n"
// + CONTENT-TYPE + "\n"
// + DATE + "\n"
// + CanonicalizedMNSHeaders
// + CanonicalizedResource))
var buff = Buffer.from(toSignString, 'utf8');
const degist = kitx.sha1(buff, this.accessKeySecret, 'binary');
return Buffer.from(degist, 'binary').toString('base64');
}
buildHeaders(method, body, resource, customHeaders) {
const date = new Date().toGMTString();
const headers = {
'date': date,
'host': this.endpointDomain,
'x-mns-date': date,
'x-mns-version': '2015-06-06'
};
if (method !== 'GET' && method !== 'HEAD') {
const contentType = 'text/xml';
const digest = kitx.md5(body, 'hex');
const md5 = Buffer.from(digest, 'utf8').toString('base64');
Object.assign(headers, {
'content-length': body.length,
'content-type': contentType,
'content-md5': md5
});
}
Object.assign(headers, customHeaders);
const signature = this.sign(method, headers, resource);
headers['authorization'] = `MNS ${this.accessKeyID}:${signature}`;
if (this.securityToken) {
headers['security-token'] = this.securityToken;
}
return headers;
}
// Queue
createQueue(name, params = {}) {
const body = toXMLBuffer('Queue', params);
const url = `/queues/${name}`;
return this.put(url, 'Queue', body, ['location']);
}
deleteQueue(name) {
return this.delete(`/queues/${name}`, 'Queue', '');
}
async listQueue(start, limit, prefix) {
var customHeaders = {};
if (typeof start !== 'undefined') {
customHeaders['x-mns-marker'] = start;
}
if (typeof limit !== 'undefined') {
customHeaders['x-mns-ret-number'] = limit;
}
if (typeof limit !== 'undefined') {
customHeaders['x-mns-prefix'] = prefix;
}
const subType = 'Queue';
const response = await this.get('/queues', 'Queues', {
headers: customHeaders
});
response.body = response.body[subType];
return response;
}
getQueueAttributes(queueName) {
return this.get(`/queues/${queueName}`, 'Queue');
}
setQueueAttributes(queueName, params = {}) {
const body = toXMLBuffer('Queue', params);
const url = `/queues/${queueName}?metaoverride=true`;
return this.put(url, 'Queue', body);
}
// Message
sendMessage(queueName, params) {
const url = `/queues/${queueName}/messages`;
const body = toXMLBuffer('Message', params);
return this.post(url, 'Message', body);
}
async batchSendMessage(queueName, params) {
const url = `/queues/${queueName}/messages`;
const subType = 'Message';
const body = toXMLBuffer('Messages', params, subType);
var response = await this.post(url, 'Messages', body);
response.body = response.body[subType];
return response;
}
receiveMessage(queueName, waitSeconds) {
var url = `/queues/${queueName}/messages`;
if (waitSeconds) {
url += `?waitseconds=${waitSeconds}`;
}
// 31000 31s +1s max waitSeconds is 30s
return this.get(url, 'Message', {timeout: 31000});
}
async batchReceiveMessage(queueName, numOfMessages, waitSeconds) {
var url = `/queues/${queueName}/messages?numOfMessages=${numOfMessages}`;
if (waitSeconds) {
url += `&waitseconds=${waitSeconds}`;
}
const subType = 'Message';
// 31000 31s +1s max waitSeconds is 30s
var response = await this.get(url, 'Messages', {timeout: 31000});
response.body = response.body[subType];
return response;
}
peekMessage(queueName) {
return this.get(`/queues/${queueName}/messages?peekonly=true`, 'Message');
}
async batchPeekMessage(queueName, numOfMessages) {
const url = `/queues/${queueName}/messages?` +
`peekonly=true&numOfMessages=${numOfMessages}`;
const subType = 'Message';
// 31000 31s +1s max waitSeconds is 30s
var response = await this.get(url, 'Messages');
response.body = response.body[subType];
return response;
}
deleteMessage(queueName, receiptHandle) {
const url = `/queues/${queueName}/messages?ReceiptHandle=${receiptHandle}`;
return this.delete(url, 'Message', '');
}
async batchDeleteMessage(queueName, receiptHandles) {
const body = toXMLBuffer('ReceiptHandles', receiptHandles);
const url = `/queues/${queueName}/messages`;
const response = await this.delete(url, 'Errors', body);
const subType = 'Error';
response.body = response.body[subType];
return response;
}
changeMessageVisibility(queueName, receiptHandle, visibilityTimeout) {
const url = `/queues/${queueName}/messages?` +
`receiptHandle=${receiptHandle}&visibilityTimeout=${visibilityTimeout}`;
return this.put(url, 'ChangeVisibility');
}
// Topic
createTopic(name, params = {}) {
const body = toXMLBuffer('Topic', params);
return this.put(`/topics/${name}`, 'Topic', body, ['location']);
}
deleteTopic() {}
async listTopic(start, limit, prefix) {
var customHeaders = {};
if (typeof start !== 'undefined') {
customHeaders['x-mns-marker'] = start;
}
if (typeof limit !== 'undefined') {
customHeaders['x-mns-ret-number'] = limit;
}
if (typeof limit !== 'undefined') {
customHeaders['x-mns-prefix'] = prefix;
}
const subType = 'Topic';
const response = await this.get('/topics', 'Topics', {
headers: customHeaders
});
response.body = response.body[subType];
return response;
}
getTopicAttributes(name) {
return this.get(`/topics/${name}`, 'Topic');
}
setTopicAttributes(name, params = {}) {
const body = toXMLBuffer('Topic', params);
const url = `/topics/${name}?metaoverride=true`;
return this.put(url, 'Topic', body);
}
// Subscription
subscribe() {}
unsubscribe() {}
listSubscriptionByTopic() {}
getSubscriptionAttributes() {}
setSubscriptionAttributes() {}
// Message
publishMessage(topic, params) {
const url = `/topics/${topic}/messages`;
const body = toXMLBuffer('Message', params);
return this.post(url, 'Message', body);
}
// Notifications
httpEndpoint() {}
}
module.exports = Client;
... ...
'use strict';
const xml2js = require('xml2js');
exports.parseXML = function (input) {
return new Promise((resolve, reject) => {
xml2js.parseString(input, (err, obj) => {
if (err) {
return reject(err);
}
resolve(obj);
});
});
};
exports.extract = function extract (arr) {
if (arr && arr.length === 1 && typeof arr[0] === 'string') {
return arr[0];
}
arr.forEach((item) => {
Object.keys(item).forEach((key) => {
item[key] = extract(item[key]);
});
});
return arr;
};
function format (params) {
var xml = '';
Object.keys(params).forEach((key) => {
const value = params[key];
if (typeof value === 'object') {
xml += `<${key}>${format(value)}</${key}>`;
} else {
xml += `<${key}>${value}</${key}>`;
}
});
return xml;
}
exports.toXMLBuffer = function (entityType, params, subType) {
var xml = '<?xml version="1.0" encoding="UTF-8"?>';
xml += `<${entityType} xmlns="http://mns.aliyuncs.com/doc/v1/">`;
if (Array.isArray(params)) {
params.forEach((item) => {
xml += `<${subType}>`;
xml += format(item);
xml += `</${subType}>`;
});
} else {
xml += format(params);
}
xml += `</${entityType}>`;
return Buffer.from(xml, 'utf8');
};
// http(s)://{AccountId}.mns.cn-beijing.aliyuncs.com
// http://{AccountId}.mns.cn-beijing-internal.aliyuncs.com
// http://{AccountId}.mns.cn-beijing-internal-vpc.aliyuncs.com
exports.getEndpoint = function (accountid, opts) {
const protocol = opts.secure ? 'https' : 'http';
let region = `${opts.region}`;
if (opts.internal) {
region += '-internal';
}
if (opts.vpc) {
region += '-vpc';
}
return {
endpoint: `${protocol}://${accountid}.mns.${region}.aliyuncs.com`,
domain: `${accountid}.mns.${region}.aliyuncs.com`
};
};
exports.getCanonicalizedMNSHeaders = function (headers) {
return Object.keys(headers)
.filter((key) => key.startsWith('x-mns-'))
.sort()
.map((key) => `${key}:${headers[key]}\n`)
.join('');
};
exports.getResponseHeaders = function (headers, attentions) {
var result = {};
attentions.forEach((key) => {
result[key] = headers[key];
});
return result;
};
... ...
{
"_args": [
[
{
"raw": "@alicloud/mns@^1.0.0-beta4",
"scope": "@alicloud",
"escapedName": "@alicloud%2fmns",
"name": "@alicloud/mns",
"rawSpec": "^1.0.0-beta4",
"spec": ">=1.0.0-beta4 <2.0.0",
"type": "range"
},
"/Users/fzy/project/koa2_Sequelize_project/node_modules/@alicloud/sms-sdk"
]
],
"_from": "@alicloud/mns@>=1.0.0-beta4 <2.0.0",
"_id": "@alicloud/mns@1.0.0-beta5",
"_inCache": true,
"_location": "/@alicloud/mns",
"_nodeVersion": "8.1.4",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/mns-1.0.0-beta5.tgz_1501596837512_0.22118755243718624"
},
"_npmUser": {
"name": "jacksontian",
"email": "shyvo1987@gmail.com"
},
"_npmVersion": "5.0.3",
"_phantomChildren": {},
"_requested": {
"raw": "@alicloud/mns@^1.0.0-beta4",
"scope": "@alicloud",
"escapedName": "@alicloud%2fmns",
"name": "@alicloud/mns",
"rawSpec": "^1.0.0-beta4",
"spec": ">=1.0.0-beta4 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/@alicloud/sms-sdk"
],
"_resolved": "https://registry.npmjs.org/@alicloud/mns/-/mns-1.0.0-beta5.tgz",
"_shasum": "aea60984f6715bbc9f7ea2f8aaef844f241f4b68",
"_shrinkwrap": null,
"_spec": "@alicloud/mns@^1.0.0-beta4",
"_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/@alicloud/sms-sdk",
"author": {
"name": "Jackson Tian"
},
"bugs": {
"url": "https://github.com/aliyun/mns-nodejs-sdk/issues"
},
"dependencies": {
"debug": "^2.6.3",
"httpx": "^2.1.1",
"kitx": "^1.2.0",
"xml2js": "^0.4.17"
},
"description": "> 该 SDK 并未完全实现所有文档所提及的功能,如果您想使用的功能并未实现,请提[issue](https://github.com/aliyun/aliyun-mns-nodejs-sdk/issues/new)以增加优先级。",
"devDependencies": {
"coveralls": "^2.13.1",
"eslint": "^3.19.0",
"expect.js": "^0.3.1",
"mocha": "^3.3.0",
"nyc": "^10.3.2"
},
"directories": {
"test": "test"
},
"dist": {
"integrity": "sha512-P4WYJSKPZb548DteQtKu8Yc1ZRdkw2Q8r7xPQthJgJIQxgTPfmiJx5hE/PEJY7GrL6N60ZS+16QIE7ErbB1xGQ==",
"shasum": "aea60984f6715bbc9f7ea2f8aaef844f241f4b68",
"tarball": "https://registry.npmjs.org/@alicloud/mns/-/mns-1.0.0-beta5.tgz"
},
"files": [
"lib",
"index.js"
],
"gitHead": "b7eb01489f2454878462d259833f4914a321c761",
"homepage": "https://github.com/aliyun/mns-nodejs-sdk#readme",
"keywords": [
"MNS",
"Message",
"Service",
"Aliyun",
"Alicloud"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"name": "rockuw",
"email": "rockuw@gmail.com"
},
{
"name": "humanhuang",
"email": "halfthink@gmail.com"
},
{
"name": "jacksontian",
"email": "shyvo1987@gmail.com"
}
],
"name": "@alicloud/mns",
"optionalDependencies": {},
"readme": "# mns-nodejs-sdk\n\n[![NPM version][npm-image]][npm-url]\n[![build status][travis-image]][travis-url]\n[![coverage][cov-image]][cov-url]\n\n[npm-image]: https://img.shields.io/npm/v/@alicloud/mns.svg?style=flat-square\n[npm-url]: https://npmjs.org/package/@alicloud/mns\n[travis-image]: https://img.shields.io/travis/aliyun/mns-nodejs-sdk/master.svg?style=flat-square\n[travis-url]: https://travis-ci.org/aliyun/mns-nodejs-sdk.svg?branch=master\n[cov-image]: https://coveralls.io/repos/aliyun/mns-nodejs-sdk/badge.svg?branch=master&service=github\n[cov-url]: https://coveralls.io/github/aliyun/mns-nodejs-sdk?branch=master\n\nDocuments: http://doxmate.cool/aliyun/mns-nodejs-sdk/api.html\n\n\n> 该 SDK 并未完全实现所有文档所提及的功能,如果您想使用的功能并未实现,请提[issue](https://github.com/aliyun/mns-nodejs-sdk/issues/new)以增加优先级。\n\n## Installation\n\n```bash\nnpm install @alicloud/mns --save\n```\n\n## API Spec\n\nSee: https://help.aliyun.com/document_detail/27475.html\n\n## Test\n\n```sh\nACCOUNT_ID=<ACCOUNT_ID> ACCESS_KEY_ID=<ACCESS_KEY_ID> ACCESS_KEY_SECRET=<ACCESS_KEY_SECRET> make test\n```\n\n## Installation\n\nYou can install it via npm/cnpm/yarn.\n\n```sh\n$ npm install @alicloud/mns --save\n```\n\n## Usage\n\n```js\nconst MNSClient = require('@alicloud/mns');\n\nconst accountid = '<account id>';\nvar client = new MNSClient(accountid, {\n region: '<region>',\n accessKeyId: '<access key id>',\n accessKeySecret: '<access key secret>',\n // optional & default\n secure: false, // use https or http\n internal: false, // use internal endpoint\n  vpc: false // use vpc endpoint\n});\n\n(async function () {\n let res;\n // create queue\n res = await client.createQueue('test-queue2');\n console.log(res);\n // list queue\n res = await client.listQueue();\n console.log(JSON.stringify(res, null, 2));\n // create topic\n res = await client.createTopic('test-topic');\n console.log(res);\n // get topic attributes\n res = await client.getTopicAttributes('test-topic');\n console.log(res);\n // publish message\n res = await client.publishMessage('<topic name>', {\n MessageBody: 'content',\n MessageAttributes: {\n DirectSMS: JSON.stringify({\n FreeSignName: '',\n TemplateCode: '<template code>',\n Type: '<type>',\n Receiver: '<phone number>',\n SmsParams: JSON.stringify({\n code: '<code>',\n product: '<product>'\n })\n })\n }\n });\n console.log(res);\n})().then((data) => {\n console.log(data);\n}, (err) => {\n console.log(err.stack);\n});\n```\n\n## License\n\nThe [MIT](LICENSE) License\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+https://github.com/aliyun/mns-nodejs-sdk.git"
},
"scripts": {
"test": "make test"
},
"version": "1.0.0-beta5"
}
... ...
## 1.0.2 (2017-01-16)
Feature:
- 返回出错的结果,挂载到返回error的data对象上,err.data = resData
\ No newline at end of file
... ...
# @alicloud/pop-core
The core SDK of POP API.
## Installation
Install it and write into package.json dependences.
```sh
$ npm install @alicloud/pop-core -S
```
## Prerequisite
Node.js >= 6.x
## Usage
The RPC style client:
```js
var RPCClient = require('@alicloud/pop-core').RPCClient;
var client = new RPCClient({
accessKeyId: '<accessKeyId>',
secretAccessKey: '<secretAccessKey>',
endpoint: '<endpoint>',
apiVersion: '<apiVersion>'
});
// => returns Promise
client.request(action, params);
// co/yield, async/await
```
The ROA style client:
```js
var ROAClient = require('@alicloud/pop-core').ROAClient;
var client = new ROAClient({
accessKeyId: '<accessKeyId>',
accessKeySecret: '<secretAccessKey>',
endpoint: '<endpoint>',
apiVersion: '<apiVersion>'
});
// => returns Promise
// request(HTTPMethod, uriPath, queries, body, headers, options);
// options => {timeout}
client.request('GET', '/regions');
// co/yield, async/await
```
## License
The MIT License
... ...
'use strict';
module.exports = require('./lib/core');
module.exports.ROAClient = require('./lib/roa');
module.exports.RPCClient = require('./lib/core');
... ...
// Type definitions for [~THE LIBRARY NAME~] [~OPTIONAL VERSION NUMBER~]
// Project: [~THE PROJECT NAME~]
// Definitions by: [~YOUR NAME~] <[~A URL FOR YOU~]>
/*~ This is the module template file for class modules.
*~ You should rename it to index.d.ts and place it in a folder with the same name as the module.
*~ For example, if you were writing a file for "super-greeter", this
*~ file should be 'super-greeter/index.d.ts'
*/
/*~ Note that ES6 modules cannot directly export class objects.
*~ This file should be imported using the CommonJS-style:
*~ import x = require('someLibrary');
*~
*~ Refer to the documentation to understand common
*~ workarounds for this limitation of ES6 modules.
*/
/*~ This declaration specifies that the class constructor function
*~ is the exported object from the file
*/
export = Core;
/*~ Write your module's methods and properties in this class */
declare class Core {
constructor(config: Core.Config);
request(action: String, params: Object, options: Object): Promise;
}
/*~ If you want to expose types from your module as well, you can
*~ place them in this block.
*/
declare namespace Core {
export interface Config {
endpoint: string;
apiVersion: string;
accessKeyId: string;
secretAccessKey: string;
}
}
... ...
'use strict';
const assert = require('assert');
const httpx = require('httpx');
const kitx = require('kitx');
const JSON = require('json-bigint');
function firstLetterUpper(str) {
return str.slice(0, 1).toUpperCase() + str.slice(1);
}
function formatParams(params) {
var keys = Object.keys(params);
var newParams = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
newParams[firstLetterUpper(key)] = params[key];
}
return newParams;
}
function timestamp() {
var date = new Date();
var YYYY = date.getUTCFullYear();
var MM = kitx.pad2(date.getUTCMonth() + 1);
var DD = kitx.pad2(date.getUTCDate());
var HH = kitx.pad2(date.getUTCHours());
var mm = kitx.pad2(date.getUTCMinutes());
var ss = kitx.pad2(date.getUTCSeconds());
// 删除掉毫秒部分
return `${YYYY}-${MM}-${DD}T${HH}:${mm}:${ss}Z`;
}
function encode(str) {
var result = encodeURIComponent(str);
return result.replace(/\!/g, '%21')
.replace(/\'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/\*/g, '%2A');
}
function repeatList(list, key, repeat) {
for (var i = 0; i < repeat.length; i++) {
var item = repeat[i];
var prefix = `${key}.${i + 1}`;
list.push([encode(prefix), encode(item)]);
}
}
function normalize(params) {
var list = [];
var keys = Object.keys(params).sort();
for (let i = 0; i < keys.length; i++) {
var key = keys[i];
var value = params[key];
if (Array.isArray(value)) {
repeatList(list, key, value);
} else {
list.push([encode(key), encode(value)]); //push []
}
}
return list;
}
function canonicalize(normalized) {
var fields = [];
for (var i = 0; i < normalized.length; i++) {
var [key, value] = normalized[i];
fields.push(key + '=' + value);
}
return fields.join('&');
}
class Core {
constructor(config, verbose) {
assert(config, 'must pass "config"');
assert(config.endpoint, 'must pass "config.endpoint"');
assert(config.apiVersion, 'must pass "config.apiVersion"');
assert(config.accessKeyId, 'must pass "config.accessKeyId"');
var accessKeySecret = config.secretAccessKey || config.accessKeySecret;
assert(accessKeySecret, 'must pass "config.accessKeySecret"');
if (config.endpoint.endsWith('/')) {
config.endpoint = config.endpoint.slice(0, -1);
}
this.endpoint = config.endpoint;
this.apiVersion = config.apiVersion;
this.accessKeyId = config.accessKeyId;
this.accessKeySecret = accessKeySecret;
this.verbose = verbose === true;
// 非 codes 里的值,将抛出异常
this.codes = new Set([200, '200', 'OK', 'Success']);
if (config.codes) {
// 合并 codes
for (var elem of config.codes) {
this.codes.add(elem);
}
}
var httpModule = this.endpoint.startsWith('https://')
? require('https') : require('http');
this.keepAliveAgent = new httpModule.Agent({
keepAlive: true,
keepAliveMsecs: 3000
});
}
request(action, params = {}, opts = {}) {
// 1. compose params
// format action until formatAction is false
if (opts.formatAction !== false) {
action = firstLetterUpper(action);
}
// format params until formatParams is false
if (opts.formatParams !== false) {
params = formatParams(params);
}
var defaults = this._buildParams();
params = Object.assign({Action: action}, defaults, params);
// 2. caculate signature
var method = (opts.method || 'GET').toUpperCase();
var normalized = normalize(params);
var canonicalized = canonicalize(normalized);
// 2.1 get string to sign
var stringToSign = `${method}&${encode('/')}&${encode(canonicalized)}`;
// 2.2 get signature
const key = this.accessKeySecret + '&';
var signature = kitx.sha1(stringToSign, key, 'base64');
// add signature
normalized.push(['Signature', encode(signature)]);
// 3. generate final url
const url = `${this.endpoint}/?${canonicalize(normalized)}`;
// 4. send request
var entry = {
url: url,
request: null,
response: null
};
if (opts && !opts.agent) {
opts.agent = this.keepAliveAgent;
}
return httpx.request(url, opts).then((response) => {
entry.request = {
headers: response.req._headers
};
entry.response = {
statusCode: response.statusCode,
headers: response.headers
};
return httpx.read(response);
}).then((buffer) => {
var json = JSON.parse(buffer);
if (json.Code && !this.codes.has(json.Code)) {
var err = new Error(json.Message);
err.name = json.Code + 'Error';
err.data = json;
err.code = json.Code;
err.url = url;
err.entry = entry;
return Promise.reject(err);
}
if (this.verbose) {
return [json, entry];
}
return json;
});
}
_buildParams() {
return {
Format: 'JSON',
SignatureMethod: 'HMAC-SHA1',
SignatureNonce: kitx.makeNonce(),
SignatureVersion: '1.0',
Timestamp: timestamp(),
AccessKeyId: this.accessKeyId,
Version: this.apiVersion,
};
}
}
module.exports = Core;
... ...
'use strict';
const assert = require('assert');
const url = require('url');
const querystring = require('querystring');
const kitx = require('kitx');
const httpx = require('httpx');
const xml2js = require('xml2js');
const JSON = require('json-bigint');
const debug = require('debug')('roa');
const pkg = require('../package.json');
function filter(value) {
return value.replace(/[\t\n\r\f]/g, ' ');
}
function parseXML(xml) {
const parser = new xml2js.Parser({
// explicitArray: false
});
return new Promise((resolve, reject) => {
parser.parseString(xml, (err, result) => {
if (err) {
return reject(err);
}
resolve(result);
});
});
}
class ACSError extends Error {
constructor(err) {
const message = err.Message[0];
const code = err.Code[0];
const hostid = err.HostId[0];
const requestid = err.RequestId[0];
super(`${message} hostid: ${hostid}, requestid: ${requestid}`);
this.code = code;
}
}
class ROAClient {
constructor(config) {
assert(config, 'must pass "config"');
assert(config.endpoint, 'must pass "config.endpoint"');
assert(config.apiVersion, 'must pass "config.apiVersion"');
assert(config.accessKeyId, 'must pass "config.accessKeyId"');
assert(config.accessKeySecret, 'must pass "config.accessKeySecret"');
this.endpoint = config.endpoint;
this.apiVersion = config.apiVersion;
this.accessKeyId = config.accessKeyId;
this.accessKeySecret = config.accessKeySecret;
this.host = url.parse(this.endpoint).hostname;
var httpModule = this.host.startsWith('https://') ? require('https') : require('http');
this.keepAliveAgent = new httpModule.Agent({
keepAlive: true,
keepAliveMsecs: 3000
});
}
buildHeaders() {
const now = new Date();
return {
accept: 'application/json',
date: now.toGMTString(),
host: this.host,
'x-acs-signature-nonce': kitx.makeNonce(),
'x-acs-signature-method': 'HMAC-SHA1',
'x-acs-signature-version': '1.0',
'x-acs-version': this.apiVersion,
'x-sdk-client': `Node.js(${process.version}), ${pkg.name}: ${pkg.version}`
};
}
getCanonicalizedHeaders(headers) {
const prefix = 'x-acs-';
const keys = Object.keys(headers);
const canonicalizedKeys = [];
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key.startsWith(prefix)) {
canonicalizedKeys.push(key);
}
}
canonicalizedKeys.sort();
var result = '';
for (let i = 0; i < canonicalizedKeys.length; i++) {
const key = canonicalizedKeys[i];
result += `${key}:${filter(headers[key]).trim()}\n`;
}
return result;
}
getCanonicalizedResource(uriPattern, query) {
const keys = Object.keys(query).sort();
if (keys.length === 0) {
return uriPattern;
}
var result = [];
for (var i = 0; i < keys.length; i++) {
const key = keys[i];
result.push(`${key}=${query[key]}`);
}
return `${uriPattern}?${result.join('&')}`;
}
buildStringToSign(method, uriPattern, headers, query) {
const accept = headers['accept'];
const contentMD5 = headers['content-md5'] || '';
const contentType = headers['content-type'] || '';
const date = headers['date'] || '';
const header = `${method}\n${accept}\n${contentMD5}\n${contentType}\n${date}\n`;
const canonicalizedHeaders = this.getCanonicalizedHeaders(headers);
const canonicalizedResource = this.getCanonicalizedResource(uriPattern, query);
return `${header}${canonicalizedHeaders}${canonicalizedResource}`;
}
signature(stringToSign) {
const utf8Buff = Buffer.from(stringToSign, 'utf8');
return kitx.sha1(utf8Buff, this.accessKeySecret, 'base64');
}
buildAuthorization(stringToSign) {
return `acs ${this.accessKeyId}:${this.signature(stringToSign)}`;
}
request(method, uriPattern, query = {}, body = '', headers = {}, opts) {
var postBody = null;
var mixHeaders = Object.assign(this.buildHeaders(), headers);
if (body) {
postBody = Buffer.from(body, 'utf8');
mixHeaders['content-md5'] = kitx.md5(postBody, 'base64');
mixHeaders['content-length'] = postBody.length;
}
var url = `${this.endpoint}${uriPattern}`;
if (Object.keys(query).length) {
url += `?${querystring.stringify(query)}`;
}
const stringToSign = this.buildStringToSign(method, uriPattern, mixHeaders, query);
debug('stringToSign: %s', stringToSign);
mixHeaders['authorization'] = this.buildAuthorization(stringToSign);
const options = Object.assign({
method,
agent: this.keepAliveAgent,
headers: mixHeaders,
data: postBody
}, opts);
return httpx.request(url, options).then((response) => {
return httpx.read(response, 'utf8').then((body) => {
const contentType = response.headers['content-type'] || '';
// JSON
if (contentType.startsWith('application/json')) {
var result = JSON.parse(body);
const statusCode = response.statusCode;
if (statusCode >= 400) {
var message = `code: ${statusCode}, ${result.Message} requestid: ${result.RequestId}`;
var err = new Error(message);
err.name = `${result.Code}Error`;
return Promise.reject(err);
}
return result;
}
if (contentType.startsWith('text/xml')) {
return parseXML(body).then((result) => {
if (result.Error) {
return Promise.reject(new ACSError(result.Error));
}
return result;
});
}
return body;
});
});
}
put(path, query, body, headers, options) {
return this.request('PUT', path, query, body, headers, options);
}
post(path, query, body, headers, options) {
return this.request('POST', path, query, body, headers, options);
}
get(path, query, headers, options) {
return this.request('GET', path, query, '', headers, options);
}
delete(path, query, headers, options) {
return this.request('DELETE', path, query, '', headers, options);
}
}
module.exports = ROAClient;
... ...
{
"_args": [
[
{
"raw": "@alicloud/pop-core@^1.3.3",
"scope": "@alicloud",
"escapedName": "@alicloud%2fpop-core",
"name": "@alicloud/pop-core",
"rawSpec": "^1.3.3",
"spec": ">=1.3.3 <2.0.0",
"type": "range"
},
"/Users/fzy/project/koa2_Sequelize_project/node_modules/@alicloud/dybaseapi"
]
],
"_from": "@alicloud/pop-core@>=1.3.3 <2.0.0",
"_id": "@alicloud/pop-core@1.5.0",
"_inCache": true,
"_location": "/@alicloud/pop-core",
"_nodeVersion": "8.5.0",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/pop-core-1.5.0.tgz_1508916658658_0.08523054211400449"
},
"_npmUser": {
"name": "jacksontian",
"email": "shyvo1987@gmail.com"
},
"_npmVersion": "5.4.2",
"_phantomChildren": {},
"_requested": {
"raw": "@alicloud/pop-core@^1.3.3",
"scope": "@alicloud",
"escapedName": "@alicloud%2fpop-core",
"name": "@alicloud/pop-core",
"rawSpec": "^1.3.3",
"spec": ">=1.3.3 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/@alicloud/dybaseapi",
"/@alicloud/dysmsapi"
],
"_resolved": "https://registry.npmjs.org/@alicloud/pop-core/-/pop-core-1.5.0.tgz",
"_shasum": "b0f44b216237ee278d4dde245f287c94daffd68d",
"_shrinkwrap": null,
"_spec": "@alicloud/pop-core@^1.3.3",
"_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/@alicloud/dybaseapi",
"author": {
"name": "Jackson Tian"
},
"bugs": {
"url": "https://github.com/aliyun/openapi-core-nodejs-sdk/issues"
},
"dependencies": {
"httpx": "^2.1.2",
"json-bigint": "^0.2.3",
"kitx": "^1.2.1",
"xml2js": "^0.4.17"
},
"description": "AliCloud POP SDK core",
"devDependencies": {
"co-mocha": "^1.1.3",
"eslint": "^3.13.0",
"expect.js": "^0.3.1",
"istanbul": "^0.4.5",
"mocha": "^3.2.0"
},
"directories": {
"test": "test"
},
"dist": {
"integrity": "sha512-GoxTbqp+4nGPwAE3swZyVpWGdolnHhW4tkwIG/g6l7sNn1gd3EuFrA4HmhaJwTrwCgZTOkV8vgYzPiCYAophOA==",
"shasum": "b0f44b216237ee278d4dde245f287c94daffd68d",
"tarball": "https://registry.npmjs.org/@alicloud/pop-core/-/pop-core-1.5.0.tgz"
},
"files": [
"lib",
"index.js"
],
"gitHead": "209d46ca673e5b8f7586d4eb863002ff25e62bd1",
"homepage": "https://github.com/aliyun/openapi-core-nodejs-sdk#readme",
"keywords": [
"Aliyun",
"AliCloud",
"OpenAPI",
"POP",
"SDK",
"Core"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"name": "chuck.ql",
"email": "kunqian434@gmail.com"
},
{
"name": "rockuw",
"email": "rockuw@gmail.com"
},
{
"name": "humanhuang",
"email": "halfthink@gmail.com"
},
{
"name": "jacksontian",
"email": "shyvo1987@gmail.com"
}
],
"name": "@alicloud/pop-core",
"optionalDependencies": {},
"readme": "# @alicloud/pop-core\n\nThe core SDK of POP API.\n\n## Installation\n\nInstall it and write into package.json dependences.\n\n```sh\n$ npm install @alicloud/pop-core -S\n```\n\n## Prerequisite\n\nNode.js >= 6.x\n\n## Usage\n\nThe RPC style client:\n\n```js\nvar RPCClient = require('@alicloud/pop-core').RPCClient;\n\nvar client = new RPCClient({\n accessKeyId: '<accessKeyId>',\n secretAccessKey: '<secretAccessKey>',\n endpoint: '<endpoint>',\n apiVersion: '<apiVersion>'\n});\n\n// => returns Promise\nclient.request(action, params);\n// co/yield, async/await\n```\n\nThe ROA style client:\n\n```js\nvar ROAClient = require('@alicloud/pop-core').ROAClient;\n\nvar client = new ROAClient({\n accessKeyId: '<accessKeyId>',\n accessKeySecret: '<secretAccessKey>',\n endpoint: '<endpoint>',\n apiVersion: '<apiVersion>'\n});\n\n// => returns Promise\n// request(HTTPMethod, uriPath, queries, body, headers, options);\n// options => {timeout}\nclient.request('GET', '/regions');\n// co/yield, async/await\n```\n\n## License\nThe MIT License\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+https://github.com/aliyun/openapi-core-nodejs-sdk.git"
},
"scripts": {
"lint": "eslint --fix lib",
"test": "mocha --require co-mocha --reporter spec test/*.test.js",
"test-cov": "istanbul cover --report html ./node_modules/.bin/_mocha -- --require co-mocha --reporter spec test/*.test.js"
},
"types": "lib/core.d.ts",
"version": "1.5.0"
}
... ...
# Created by .ignore support plugin (hsz.mobi)
### Example user template template
### Example user template
# IntelliJ project files
.idea
*.iml
out
gen
node_modules/
... ...
### 安装
``` javascript
$ npm install @alicloud/sms-sdk --save
```
### 使用方法
1. 安装@alicloud/sms-sdk,请需要根据官方文档做一些配置
2. 产品文档: https://dysms.console.aliyun.com/dysms.htm
### DEMO
``` javascript
/**
* 云通信基础能力业务短信发送、查询详情以及消费消息示例,供参考。
* Created on 2017-07-31
*/
const SMSClient = require('./../index')
// ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换
const accessKeyId = 'yourAccessKeyId'
const secretAccessKey = 'yourAccessKeySecret'
//在云通信页面开通相应业务消息后,就能在页面上获得对应的queueName,不用填最后面一段
const queueName = 'Alicom-Queue-1092397003988387-'
//初始化sms_client
let smsClient = new SMSClient({accessKeyId, secretAccessKey})
//短信回执报告
smsClient.receiveMsg(0, queueName).then(function (res) {
//消息体需要base64解码
let {code, body}=res
if (code === 200) {
//处理消息体,messagebody
console.log(body)
}
}, function (err) {
console.log(err)
})
//短信上行报告
smsClient.receiveMsg(1, queueName).then(function (res) {
//消息体需要base64解码
let {code, body}=res
if (code === 200) {
//处理消息体,messagebody
console.log(body)
}
}, function (err) {
console.log(err)
})
//查询短信发送详情
smsClient.queryDetail({
PhoneNumber: '1500000000',
SendDate: '20170731',
PageSize: '10',
CurrentPage: "1"
}).then(function (res) {
let {Code, SmsSendDetailDTOs}=res
if (Code === 'OK') {
//处理发送详情内容
console.log(SmsSendDetailDTOs)
}
}, function (err) {
//处理错误
console.log(err)
})
//发送短信
smsClient.sendSMS({
PhoneNumbers: '1500000000',
SignName: '云通信产品',
TemplateCode: 'SMS_000000',
TemplateParam: '{"code":"12345","product":"云通信"}'
}).then(function (res) {
let {Code}=res
if (Code === 'OK') {
//处理返回参数
console.log(res)
}
}, function (err) {
console.log(err)
})
```
\ No newline at end of file
... ...
/**
* 云通信基础能力业务短信发送、查询详情以及消费消息示例,供参考。
* Created on 2017-07-31
*/
const SMSClient = require('./../index')
// ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换
const accessKeyId = 'yourAccessKeyId'
const secretAccessKey = 'yourAccessKeySecret'
//在云通信页面开通相应业务消息后,就能在页面上获得对应的queueName,不用填最后面一段
const queueName = 'Alicom-Queue-1092397003988387-'
//初始化sms_client
let smsClient = new SMSClient({accessKeyId, secretAccessKey})
//短信回执报告
smsClient.receiveMsg(0, queueName).then(function (res) {
//消息体需要base64解码
let {code, body}=res
if (code === 200) {
//处理消息体,messagebody
console.log(body)
}
}, function (err) {
console.log(err)
})
//短信上行报告
smsClient.receiveMsg(1, queueName).then(function (res) {
//消息体需要base64解码
let {code, body}=res
if (code === 200) {
//处理消息体,messagebody
console.log(body)
}
}, function (err) {
console.log(err)
})
//查询短信发送详情
smsClient.queryDetail({
PhoneNumber: '1500000000',
SendDate: '20170731',
PageSize: '10',
CurrentPage: "1"
}).then(function (res) {
let {Code, SmsSendDetailDTOs}=res
if (Code === 'OK') {
//处理发送详情内容
console.log(SmsSendDetailDTOs)
}
}, function (err) {
//处理错误
console.log(err)
})
//发送短信
smsClient.sendSMS({
PhoneNumbers: '1500000000',
SignName: '云通信产品',
TemplateCode: 'SMS_000000',
TemplateParam: '{"code":"12345","product":"云通信"}'
}).then(function (res) {
let {Code}=res
if (Code === 'OK') {
//处理返回参数
console.log(res)
}
}, function (err) {
console.log(err)
})
... ...
'use strict';
const DysmsapiClient = require('@alicloud/dysmsapi')
const DybaseapiClient = require('@alicloud/dybaseapi')
const MNSClient = require('@alicloud/mns')
// 短信回执报告:SmsReport,短信上行:SmsUp
const msgTypeList = ["SmsReport", "SmsUp"]
const DYSMSAPI_ENDPOINT = 'http://dysmsapi.aliyuncs.com'
const DYBASEAPI_ENDPOINT = 'http://dybaseapi.aliyuncs.com'
class SMSClient {
constructor(options) {
let {accessKeyId, secretAccessKey}=options
if (!accessKeyId) {
throw new TypeError('parameter "accessKeyId" is required');
}
if (!secretAccessKey) {
throw new TypeError('parameter "secretAccessKey" is required');
}
this.dysmsapiClient = new DysmsapiClient({accessKeyId, secretAccessKey, endpoint: DYSMSAPI_ENDPOINT})
this.dybaseClient = new DybaseapiClient({accessKeyId, secretAccessKey, endpoint: DYBASEAPI_ENDPOINT})
this.expire = []
this.mnsClient = []
}
//发送短信
sendSMS(params) {
return this.dysmsapiClient.sendSms(params)
}
//查询详情
queryDetail(params) {
return this.dysmsapiClient.querySendDetails(params)
}
//失效时间与当前系统时间比较,提前2分钟刷新token
_refresh(type) {
return this.expire[type] - new Date().getTime() > 2 * 60 * 1000
}
//获取token
_getToken(type) {
let msgType = msgTypeList[type]
return this.dybaseClient.queryTokenForMnsQueue({MessageType: msgType})
}
//根据类型获取mnsclient实例
async _getMNSClient(type) {
if (this.mnsClient && (this.mnsClient[type] instanceof MNSClient) && this._refresh(type)) {
return this.mnsClient[type]
}
let {
MessageTokenDTO:{
SecurityToken,
AccessKeyId,
AccessKeySecret
}
}=await this._getToken(type)
if (!(AccessKeyId && AccessKeySecret && SecurityToken)) {
throw new TypeError('get token fail')
}
let mnsClient = new MNSClient('1943695596114318', {
securityToken: SecurityToken,
region: 'cn-hangzhou',
accessKeyId: AccessKeyId,
accessKeySecret: AccessKeySecret,
// optional & default
secure: false, // use https or http
internal: false, // use internal endpoint
vpc: false // use vpc endpoint
})
this.mnsClient[type] = mnsClient
this.expire[type] = (new Date().getTime() + 10 * 60 * 1000)
return mnsClient
}
//typeIndex :0 为回执,1为上行
async receiveMsg(typeIndex = 0, preQueueName, waitSeconds = 10) {
let mnsClient = await this._getMNSClient(typeIndex)
return await mnsClient.receiveMessage(preQueueName + msgTypeList[typeIndex], waitSeconds)
}
}
module.exports = SMSClient
... ...
{
"name": "aliyun-dysms-sdk",
"version": "1.0.0",
"lockfileVersion": 1,
"dependencies": {
"@alicloud/dybaseapi": {
"version": "1.0.0",
"resolved": "http://registry.npm.alibaba-inc.com/@alicloud/dybaseapi/download/@alicloud/dybaseapi-1.0.0.tgz",
"dependencies": {
"@alicloud/pop-core": {
"version": "1.3.3",
"resolved": "http://registry.npm.alibaba-inc.com/@alicloud/pop-core/download/@alicloud/pop-core-1.3.3.tgz",
"dependencies": {
"httpx": {
"version": "2.1.2",
"resolved": "http://registry.npm.alibaba-inc.com/httpx/download/httpx-2.1.2.tgz"
},
"kitx": {
"version": "1.2.1",
"resolved": "http://registry.npm.alibaba-inc.com/kitx/download/kitx-1.2.1.tgz"
},
"xml2js": {
"version": "0.4.17",
"resolved": "http://registry.npm.alibaba-inc.com/xml2js/download/xml2js-0.4.17.tgz"
}
}
}
}
},
"@alicloud/dysmsapi": {
"version": "https://registry.npmjs.org/@alicloud/dysmsapi/-/dysmsapi-1.0.0.tgz",
"integrity": "sha1-cS3dfs/1wGNTejwwSGfS6uAv/JU="
},
"@alicloud/mns": {
"version": "1.0.0-beta4",
"resolved": "https://registry.npmjs.org/@alicloud/mns/-/mns-1.0.0-beta4.tgz",
"integrity": "sha512-bN/OoL3HuaXKRerUa+sWaGvhH58PTONEPTkujwOGxd0ZSg1Zs+Pk5WdXokm2yeddVfYJmU6DkuUOmox/E08+Wg=="
},
"@alicloud/pop-core": {
"version": "https://registry.npmjs.org/@alicloud/pop-core/-/pop-core-1.3.3.tgz",
"integrity": "sha1-ClZ8Cuxg4S1E4pVk52ZXvuvNvW8="
},
"assertion-error": {
"version": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.0.2.tgz",
"integrity": "sha1-E8pRXYYgbaC6xm6DTdOX2HWBCUw=",
"dev": true
},
"chai": {
"version": "https://registry.npmjs.org/chai/-/chai-4.0.2.tgz",
"integrity": "sha1-L3MnxN5vOF3XeHmZ4qsCaXoyuDs=",
"dev": true
},
"check-error": {
"version": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz",
"integrity": "sha1-V00xLt2Iu13YkS6Sht1sCu1KrII=",
"dev": true
},
"debug": {
"version": "https://registry.npmjs.org/debug/-/debug-2.6.8.tgz",
"integrity": "sha1-5zFTHKLt4n0YgiJCfaF4IdaP9Pw="
},
"deep-eql": {
"version": "https://registry.npmjs.org/deep-eql/-/deep-eql-2.0.2.tgz",
"integrity": "sha1-sbrAblbwp2d3aG1Qyf63XC7XZ5o=",
"dev": true,
"dependencies": {
"type-detect": {
"version": "https://registry.npmjs.org/type-detect/-/type-detect-3.0.0.tgz",
"integrity": "sha1-RtDMhVOrt7E6NSsNbeov1Y8tm1U=",
"dev": true
}
}
},
"get-func-name": {
"version": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz",
"integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=",
"dev": true
},
"httpx": {
"version": "https://registry.npmjs.org/httpx/-/httpx-2.1.2.tgz",
"integrity": "sha1-Wa7BWK1o3wqtNopymyXyKo2/sRQ="
},
"kitx": {
"version": "https://registry.npmjs.org/kitx/-/kitx-1.2.1.tgz",
"integrity": "sha1-uvvi526hmbATleEwEcdnCo/ULT8="
},
"lodash": {
"version": "http://registry.npm.alibaba-inc.com/lodash/download/lodash-4.17.4.tgz",
"integrity": "sha1-eCA6TRwyiuHYbcpkYONptX9AVa4="
},
"ms": {
"version": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g="
},
"pathval": {
"version": "https://registry.npmjs.org/pathval/-/pathval-1.1.0.tgz",
"integrity": "sha1-uULm1L3mUwBe9rcTYd74cn0GReA=",
"dev": true
},
"sax": {
"version": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz",
"integrity": "sha1-KBYjTiN4vdxOU1T6tcqold9xANk="
},
"type-detect": {
"version": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.3.tgz",
"integrity": "sha1-Dj8mcLRAmbC0bChNE2p+9Jx0wuo=",
"dev": true
},
"xml2js": {
"version": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.17.tgz",
"integrity": "sha1-F76T6q4/O3eTWceVtBlwWogX6Gg="
},
"xmlbuilder": {
"version": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-4.2.1.tgz",
"integrity": "sha1-qlijBBoGb5DqoWwvU4n/GfP0YaU="
}
}
}
... ...
{
"_args": [
[
{
"raw": "@alicloud/sms-sdk",
"scope": "@alicloud",
"escapedName": "@alicloud%2fsms-sdk",
"name": "@alicloud/sms-sdk",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"/Users/fzy/project/koa2_Sequelize_project"
]
],
"_from": "@alicloud/sms-sdk@latest",
"_id": "@alicloud/sms-sdk@1.0.2",
"_inCache": true,
"_location": "/@alicloud/sms-sdk",
"_nodeVersion": "6.9.2",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/sms-sdk-1.0.2.tgz_1502680187908_0.7891042081173509"
},
"_npmUser": {
"name": "chuck.ql",
"email": "kunqian434@gmail.com"
},
"_npmVersion": "3.10.9",
"_phantomChildren": {},
"_requested": {
"raw": "@alicloud/sms-sdk",
"scope": "@alicloud",
"escapedName": "@alicloud%2fsms-sdk",
"name": "@alicloud/sms-sdk",
"rawSpec": "",
"spec": "latest",
"type": "tag"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/@alicloud/sms-sdk/-/sms-sdk-1.0.2.tgz",
"_shasum": "8842ed88bc88e55a9deaf28ba5b2c872aa48f5c1",
"_shrinkwrap": null,
"_spec": "@alicloud/sms-sdk",
"_where": "/Users/fzy/project/koa2_Sequelize_project",
"author": {
"name": "chuck.ql"
},
"dependencies": {
"@alicloud/dybaseapi": "^1.0.0",
"@alicloud/dysmsapi": "^1.0.0",
"@alicloud/mns": "^1.0.0-beta4"
},
"description": "阿里云-云通信-短信产品SDK",
"devDependencies": {
"chai": "^4.0.2"
},
"directories": {},
"dist": {
"shasum": "8842ed88bc88e55a9deaf28ba5b2c872aa48f5c1",
"tarball": "https://registry.npmjs.org/@alicloud/sms-sdk/-/sms-sdk-1.0.2.tgz"
},
"gitHead": "95da6c8fa4096b459f1dbe5ed7a15528b42aaef4",
"keywords": [
"SDK",
"云通信",
"阿里云",
"短信",
"Node.js"
],
"license": "ISC",
"main": "index.js",
"maintainers": [
{
"name": "chuck.ql",
"email": "kunqian434@gmail.com"
},
{
"name": "rockuw",
"email": "rockuw@gmail.com"
},
{
"name": "humanhuang",
"email": "halfthink@gmail.com"
},
{
"name": "jacksontian",
"email": "shyvo1987@gmail.com"
}
],
"name": "@alicloud/sms-sdk",
"optionalDependencies": {},
"readme": "### 安装\n\n``` javascript\n $ npm install @alicloud/sms-sdk --save\n```\n\n### 使用方法\n1. 安装@alicloud/sms-sdk,请需要根据官方文档做一些配置\n2. 产品文档: https://dysms.console.aliyun.com/dysms.htm\n\n### DEMO\n\n``` javascript\n/**\n * 云通信基础能力业务短信发送、查询详情以及消费消息示例,供参考。\n * Created on 2017-07-31\n */\n\nconst SMSClient = require('./../index')\n\n// ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换\nconst accessKeyId = 'yourAccessKeyId'\nconst secretAccessKey = 'yourAccessKeySecret'\n\n//在云通信页面开通相应业务消息后,就能在页面上获得对应的queueName,不用填最后面一段\nconst queueName = 'Alicom-Queue-1092397003988387-'\n\n//初始化sms_client\nlet smsClient = new SMSClient({accessKeyId, secretAccessKey})\n\n//短信回执报告\nsmsClient.receiveMsg(0, queueName).then(function (res) {\n //消息体需要base64解码\n let {code, body}=res\n if (code === 200) {\n //处理消息体,messagebody\n console.log(body)\n }\n}, function (err) {\n console.log(err)\n})\n\n//短信上行报告\nsmsClient.receiveMsg(1, queueName).then(function (res) {\n //消息体需要base64解码\n let {code, body}=res\n if (code === 200) {\n //处理消息体,messagebody\n console.log(body)\n }\n}, function (err) {\n console.log(err)\n})\n\n\n//查询短信发送详情\nsmsClient.queryDetail({\n PhoneNumber: '1500000000',\n SendDate: '20170731',\n PageSize: '10',\n CurrentPage: \"1\"\n}).then(function (res) {\n let {Code, SmsSendDetailDTOs}=res\n if (Code === 'OK') {\n //处理发送详情内容\n console.log(SmsSendDetailDTOs)\n }\n}, function (err) {\n //处理错误\n console.log(err)\n})\n\n//发送短信\nsmsClient.sendSMS({\n PhoneNumbers: '1500000000',\n SignName: '云通信产品',\n TemplateCode: 'SMS_000000',\n TemplateParam: '{\"code\":\"12345\",\"product\":\"云通信\"}'\n}).then(function (res) {\n let {Code}=res\n if (Code === 'OK') {\n //处理返回参数\n console.log(res)\n }\n}, function (err) {\n console.log(err)\n})\n```",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git@gitlab.alibaba-inc.com:alidayu/aliyun-dysms-sdk.git"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"version": "1.0.2"
}
... ...
httpx
===========
http(s) module with power.
[![NPM version][npm-image]][npm-url]
[![build status][travis-image]][travis-url]
[![Coverage Status](https://coveralls.io/repos/JacksonTian/httpx/badge.svg?branch=master&service=github)](https://coveralls.io/github/JacksonTian/httpx?branch=master)
[![David deps][david-image]][david-url]
[![npm download][download-image]][download-url]
[npm-image]: https://img.shields.io/npm/v/httpx.svg?style=flat-square
[npm-url]: https://npmjs.org/package/httpx
[travis-image]: https://img.shields.io/travis/JacksonTian/httpx.svg?style=flat-square
[travis-url]: https://travis-ci.org/JacksonTian/httpx
[david-image]: https://img.shields.io/david/JacksonTian/httpx.svg?style=flat-square
[david-url]: https://david-dm.org/JacksonTian/httpx
[download-image]: https://img.shields.io/npm/dm/httpx.svg?style=flat-square
[download-url]: https://npmjs.org/package/httpx
## Installation
```bash
$ npm install httpx --save
```
## Usage
```js
'use strict';
const httpx = require('httpx');
httpx.request('http://www.baidu.com/').then((response) => {
response.pipe(process.stdout);
response.on('end', () => {
process.stdout.write('\n');
});
}, (err) => {
// on error
});
```
Or with `co`.
```js
co(function* () {
var response = yield httpx.request('http://www.baidu.com/');
response.pipe(process.stdout);
response.on('end', () => {
process.stdout.write('\n');
});
});
```
Or with `async/await`.
```js
(async function () {
var response = await httpx.request('http://www.baidu.com/');
response.pipe(process.stdout);
response.on('end', () => {
process.stdout.write('\n');
});
})();
```
## API
### `httpx.request(url[, options])`
- **url** String | Object - The URL to request, either a String or a Object that return by [url.parse](http://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost).
- ***options*** Object - Optional
- ***method*** String - Request method, defaults to `GET`. Could be `GET`, `POST`, `DELETE` or `PUT`.
- ***data*** String | [Buffer](http://nodejs.org/api/buffer.html) | Readable - Manually set the content of payload.
- ***headers*** Object - Request headers.
- ***timeout*** Number - Request timeout in milliseconds. Defaults to 3000. When timeout happen, will return `RequestTimeout`.
- ***agent*** [http.Agent](http://nodejs.org/api/http.html#http_class_http_agent) - HTTP/HTTPS Agent object.
Set `false` if you does not use agent.
- ***beforeRequest*** Function - Before request hook, you can change every thing here.
- ***compression*** Boolean - Enable compression support. Tell server side responses compressed data
### `httpx.read(response[, encoding])`
- **response** Response - the Client response. Don't setEncoding() for the response.
- **encoding** String - Optional.
## License
The MIT license
... ...
'use strict';
const zlib = require('zlib');
const http = require('http');
const https = require('https');
const parse = require('url').parse;
const format = require('url').format;
const debug = require('debug')('httpx');
const httpAgent = new http.Agent({ keepAlive: true });
const httpsAgent = new https.Agent({ keepAlive: true });
const TIMEOUT = 3000; // 3s
var append = function (err, name, message) {
err.name = name + err.name;
err.message = message + '\n' + err.message;
return err;
};
exports.request = function (url, opts) {
// request(url)
opts || (opts = {});
const parsed = typeof url === 'string' ? parse(url) : url;
const timeout = opts.timeout || TIMEOUT;
const isHttps = parsed.protocol === 'https:';
const method = (opts.method || 'GET').toUpperCase();
const defaultAgent = isHttps ? httpsAgent : httpAgent;
const agent = opts.agent || defaultAgent;
var options = {
host: parsed.hostname || 'localhost',
path: parsed.path || '/',
method: method,
port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
agent: agent,
headers: opts.headers || {}
};
if (opts.compression) {
options.headers['accept-encoding'] = 'gzip,deflate';
}
const httplib = isHttps ? https : http;
if (typeof opts.beforeRequest === 'function') {
options = opts.beforeRequest(options);
}
return new Promise((resolve, reject) => {
const startTime = Date.now();
const request = httplib.request(options);
const body = opts.data;
var timer;
var cleanup = () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
};
var fulfilled = (response) => {
cleanup();
if (debug.enabled) {
const requestHeaders = response.req._header;
requestHeaders.split('\r\n').forEach((line) => {
debug('> %s', line);
});
debug('< HTTP/%s %s %s', response.httpVersion, response.statusCode, response.statusMessage);
Object.keys(response.headers).forEach((key) => {
debug('< %s: %s', key, response.headers[key]);
});
}
resolve(response);
};
var rejected = (err) => {
cleanup();
err.message += ` ${method} ${format(parsed)} failed.`;
reject(err);
};
var abort = (err) => {
request.abort();
rejected(err);
};
// string
if (!body || 'string' === typeof body || body instanceof Buffer) {
request.end(body);
} else if ('function' === typeof body.pipe) { // stream
body.pipe(request);
body.once('error', (err) => {
abort(append(err, 'HttpX', 'Stream occor error'));
});
}
request.on('response', fulfilled);
request.on('error', rejected);
// for timeout
timer = setTimeout(() => {
timer = null;
var err = new Error();
var message = `${method} ${format(parsed)} timeout(${timeout}).`;
abort(append(err, 'RequestTimeout', message));
}, timeout);
});
};
exports.read = function (response, encoding) {
var readable = response;
switch (response.headers['content-encoding']) {
// or, just use zlib.createUnzip() to handle both cases
case 'gzip':
readable = response.pipe(zlib.createGunzip());
break;
case 'deflate':
readable = response.pipe(zlib.createInflate());
break;
default:
break;
}
return new Promise((resolve, reject) => {
var cleanup = function () {
// cleanup
readable.removeListener('error', onError);
readable.removeListener('data', onData);
readable.removeListener('end', onEnd);
};
const bufs = [];
var size = 0;
var onData = function (buf) {
bufs.push(buf);
size += buf.length;
};
var onError = function (err) {
cleanup();
reject(err);
};
var onEnd = function () {
cleanup();
var buff = Buffer.concat(bufs, size);
debug('');
if (encoding) {
const result = buff.toString(encoding);
debug(result);
return resolve(result);
}
debug('Buffer <ignored>');
resolve(buff);
};
readable.on('error', onError);
readable.on('data', onData);
readable.on('end', onEnd);
});
};
... ...
{
"_args": [
[
{
"raw": "httpx@^2.1.2",
"scope": null,
"escapedName": "httpx",
"name": "httpx",
"rawSpec": "^2.1.2",
"spec": ">=2.1.2 <3.0.0",
"type": "range"
},
"/Users/fzy/project/koa2_Sequelize_project/node_modules/@alicloud/pop-core"
]
],
"_from": "httpx@>=2.1.2 <3.0.0",
"_id": "httpx@2.1.2",
"_inCache": true,
"_location": "/httpx",
"_nodeVersion": "7.7.4",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/httpx-2.1.2.tgz_1495703755237_0.4486262151040137"
},
"_npmUser": {
"name": "jacksontian",
"email": "shyvo1987@gmail.com"
},
"_npmVersion": "4.1.2",
"_phantomChildren": {},
"_requested": {
"raw": "httpx@^2.1.2",
"scope": null,
"escapedName": "httpx",
"name": "httpx",
"rawSpec": "^2.1.2",
"spec": ">=2.1.2 <3.0.0",
"type": "range"
},
"_requiredBy": [
"/@alicloud/mns",
"/@alicloud/pop-core"
],
"_resolved": "https://registry.npmjs.org/httpx/-/httpx-2.1.2.tgz",
"_shasum": "59aec158ad68df0aad368a729b25f22a8dbfb114",
"_shrinkwrap": null,
"_spec": "httpx@^2.1.2",
"_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/@alicloud/pop-core",
"author": {
"name": "Jackson Tian"
},
"bugs": {
"url": "https://github.com/JacksonTian/httpx/issues"
},
"dependencies": {
"debug": "^2.2.0"
},
"description": "http(s) module with power",
"devDependencies": {
"co-mocha": "^1.1.3",
"coveralls": "^2.11.15",
"eslint": "^3.13.1",
"istanbul": "^0.4.5",
"mocha": "^3.2.0"
},
"directories": {},
"dist": {
"shasum": "59aec158ad68df0aad368a729b25f22a8dbfb114",
"tarball": "https://registry.npmjs.org/httpx/-/httpx-2.1.2.tgz"
},
"files": [
"lib"
],
"gitHead": "bbe3ce084ae2818be6051d0018ab2618e5f2f24a",
"homepage": "https://github.com/JacksonTian/httpx",
"license": "MIT",
"main": "lib/index.js",
"maintainers": [
{
"name": "jacksontian",
"email": "shyvo1987@gmail.com"
}
],
"name": "httpx",
"optionalDependencies": {},
"readme": "httpx\n===========\nhttp(s) module with power.\n\n[![NPM version][npm-image]][npm-url]\n[![build status][travis-image]][travis-url]\n[![Coverage Status](https://coveralls.io/repos/JacksonTian/httpx/badge.svg?branch=master&service=github)](https://coveralls.io/github/JacksonTian/httpx?branch=master)\n[![David deps][david-image]][david-url]\n[![npm download][download-image]][download-url]\n\n[npm-image]: https://img.shields.io/npm/v/httpx.svg?style=flat-square\n[npm-url]: https://npmjs.org/package/httpx\n[travis-image]: https://img.shields.io/travis/JacksonTian/httpx.svg?style=flat-square\n[travis-url]: https://travis-ci.org/JacksonTian/httpx\n[david-image]: https://img.shields.io/david/JacksonTian/httpx.svg?style=flat-square\n[david-url]: https://david-dm.org/JacksonTian/httpx\n[download-image]: https://img.shields.io/npm/dm/httpx.svg?style=flat-square\n[download-url]: https://npmjs.org/package/httpx\n\n## Installation\n\n```bash\n$ npm install httpx --save\n```\n\n## Usage\n\n```js\n'use strict';\n\nconst httpx = require('httpx');\n\nhttpx.request('http://www.baidu.com/').then((response) => {\n response.pipe(process.stdout);\n\n response.on('end', () => {\n process.stdout.write('\\n');\n });\n}, (err) => {\n // on error\n});\n```\n\nOr with `co`.\n\n```js\nco(function* () {\n var response = yield httpx.request('http://www.baidu.com/');\n\n response.pipe(process.stdout);\n\n response.on('end', () => {\n process.stdout.write('\\n');\n });\n});\n```\n\nOr with `async/await`.\n\n```js\n(async function () {\n var response = await httpx.request('http://www.baidu.com/');\n\n response.pipe(process.stdout);\n\n response.on('end', () => {\n process.stdout.write('\\n');\n });\n})();\n```\n\n## API\n\n### `httpx.request(url[, options])`\n\n- **url** String | Object - The URL to request, either a String or a Object that return by [url.parse](http://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost).\n- ***options*** Object - Optional\n - ***method*** String - Request method, defaults to `GET`. Could be `GET`, `POST`, `DELETE` or `PUT`.\n - ***data*** String | [Buffer](http://nodejs.org/api/buffer.html) | Readable - Manually set the content of payload.\n - ***headers*** Object - Request headers.\n - ***timeout*** Number - Request timeout in milliseconds. Defaults to 3000. When timeout happen, will return `RequestTimeout`.\n - ***agent*** [http.Agent](http://nodejs.org/api/http.html#http_class_http_agent) - HTTP/HTTPS Agent object.\n Set `false` if you does not use agent.\n - ***beforeRequest*** Function - Before request hook, you can change every thing here.\n - ***compression*** Boolean - Enable compression support. Tell server side responses compressed data\n\n### `httpx.read(response[, encoding])`\n\n- **response** Response - the Client response. Don't setEncoding() for the response.\n- **encoding** String - Optional.\n\n## License\nThe MIT license\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+https://github.com/JacksonTian/httpx.git"
},
"scripts": {
"test": "make test"
},
"version": "2.1.2"
}
... ...
lib-cov
*.seed
*.log
*.csv
*.dat
*.out
*.pid
*.gz
.*.swp
node_modules
pids
logs
results
npm-debug.log
... ...
language: node_js
node_js:
- "0.10"
- "0.11"
... ...
The MIT License (MIT)
Copyright (c) 2013 Andrey Sidorov
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
... ...
json-bigint
===========
[![Build Status](https://secure.travis-ci.org/sidorares/json-bigint.png)](http://travis-ci.org/sidorares/json-bigint)
[![NPM](https://nodei.co/npm/json-bigint.png?downloads=true&stars=true)](https://nodei.co/npm/json-bigint/)
JSON.parse/stringify with bigints support. Based on Douglas Crockford [JSON.js](https://github.com/douglascrockford/JSON-js) package and [bignumber.js](https://github.com/MikeMcl/bignumber.js) library.
While most JSON parsers assume numeric values have same precision restrictions as IEEE 754 double, JSON specification _does not_ say anything about number precision. Any floating point number in decimal (optionally scientific) notation is valid JSON value. It's a good idea to serialize values which might fall out of IEEE 754 integer precision as strings in your JSON api, but `{ "value" : 9223372036854775807}`, for example, is still a valid RFC4627 JSON string, and in most JS runtimes the result of `JSON.parse` is this object: `{ value: 9223372036854776000 }`
==========
example:
```js
var JSONbig = require('json-bigint');
var json = '{ "value" : 9223372036854775807, "v2": 123 }';
console.log('Input:', json);
console.log('');
console.log('node.js bult-in JSON:')
var r = JSON.parse(json);
console.log('JSON.parse(input).value : ', r.value.toString());
console.log('JSON.stringify(JSON.parse(input)):', JSON.stringify(r));
console.log('\n\nbig number JSON:');
var r1 = JSONbig.parse(json);
console.log('JSON.parse(input).value : ', r1.value.toString());
console.log('JSON.stringify(JSON.parse(input)):', JSONbig.stringify(r1));
```
Output:
```
Input: { "value" : 9223372036854775807, "v2": 123 }
node.js bult-in JSON:
JSON.parse(input).value : 9223372036854776000
JSON.stringify(JSON.parse(input)): {"value":9223372036854776000,"v2":123}
big number JSON:
JSON.parse(input).value : 9223372036854775807
JSON.stringify(JSON.parse(input)): {"value":9223372036854775807,"v2":123}
```
### Options
The behaviour of the parser is somewhat configurable through 'options'
#### options.strict, boolean, default false
Specifies the parsing should be "strict" towards reporting duplicate-keys in the parsed string.
The default follows what is allowed in standard json and resembles the behavior of JSON.parse, but overwrites any previous values with the last one assigned to the duplicate-key.
Setting options.strict = true will fail-fast on such duplicate-key occurances and thus warn you upfront of possible lost information.
example:
```js
var JSONbig = require('json-bigint');
var JSONstrict = require('json-bigint')({"strict": true});
var dupkeys = '{ "dupkey": "value 1", "dupkey": "value 2"}';
console.log('\n\nDuplicate Key test with both lenient and strict JSON parsing');
console.log('Input:', dupkeys);
var works = JSONbig.parse(dupkeys);
console.log('JSON.parse(dupkeys).dupkey: %s', works.dupkey);
var fails = "will stay like this";
try {
fails = JSONstrict.parse(dupkeys);
console.log('ERROR!! Should never get here');
} catch (e) {
console.log('Succesfully catched expected exception on duplicate keys: %j', e);
}
```
Output
```
Duplicate Key test with big number JSON
Input: { "dupkey": "value 1", "dupkey": "value 2"}
JSON.parse(dupkeys).dupkey: value 2
Succesfully catched expected exception on duplicate keys: {"name":"SyntaxError","message":"Duplicate key \"dupkey\"","at":33,"text":"{ \"dupkey\": \"value 1\", \"dupkey\": \"value 2\"}"}
```
#### options.storeAsString, boolean, default false
Specifies if BigInts should be stored in the object as a string, rather than the default BigNumber.
Note that this is a dangerous behavior as it breaks the default functionality of being able to convert back-and-forth without data type changes (as this will convert all BigInts to be-and-stay strings).
example:
```js
var JSONbig = require('json-bigint');
var JSONbigString = require('json-bigint')({"storeAsString": true});
var key = '{ "key": 1234567890123456789 }';
console.log('\n\nStoring the BigInt as a string, instead of a BigNumber');
console.log('Input:', key);
var withInt = JSONbig.parse(key);
var withString = JSONbigString.parse(key);
console.log('Default type: %s, With option type: %s', typeof withInt.key, typeof withString.key);
```
Output
```
Storing the BigInt as a string, instead of a BigNumber
Input: { "key": 1234567890123456789 }
Default type: object, With option type: string
```
### Links:
- [RFC4627: The application/json Media Type for JavaScript Object Notation (JSON)](http://www.ietf.org/rfc/rfc4627.txt)
- [Re: \[Json\] Limitations on number size?](http://www.ietf.org/mail-archive/web/json/current/msg00297.html)
- [Is there any proper way to parse JSON with large numbers? (long, bigint, int64)](http://stackoverflow.com/questions/18755125/node-js-is-there-any-proper-way-to-parse-json-with-large-numbers-long-bigint)
- [What is JavaScript's Max Int? What's the highest Integer value a Number can go to without losing precision?](http://stackoverflow.com/questions/307179/what-is-javascripts-max-int-whats-the-highest-integer-value-a-number-can-go-t)
- [Large numbers erroneously rounded in Javascript](http://stackoverflow.com/questions/1379934/large-numbers-erroneously-rounded-in-javascript)
... ...
var json_stringify = require('./lib/stringify.js').stringify;
var json_parse = require('./lib/parse.js');
module.exports = function(options) {
return {
parse: json_parse(options),
stringify: json_stringify
}
};
//create the default method members with no options applied for backwards compatibility
module.exports.parse = json_parse();
module.exports.stringify = json_stringify;
... ...
var BigNumber = null;
/*
json_parse.js
2012-06-20
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
This file creates a json_parse function.
During create you can (optionally) specify some behavioural switches
require('json-bigint')(options)
The optional options parameter holds switches that drive certain
aspects of the parsing process:
* options.strict = true will warn about duplicate-key usage in the json.
The default (strict = false) will silently ignore those and overwrite
values for keys that are in duplicate use.
The resulting function follows this signature:
json_parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = json_parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
*/
/*members "", "\"", "\/", "\\", at, b, call, charAt, f, fromCharCode,
hasOwnProperty, message, n, name, prototype, push, r, t, text
*/
var json_parse = function (options) {
"use strict";
// This is a function that can parse a JSON text, producing a JavaScript
// data structure. It is a simple, recursive descent parser. It does not use
// eval or regular expressions, so it can be used as a model for implementing
// a JSON parser in other languages.
// We are defining the function inside of another function to avoid creating
// global variables.
// Default options one can override by passing options to the parse()
var _options = {
"strict": false, // not being strict means do not generate syntax errors for "duplicate key"
"storeAsString": false // toggles whether the values should be stored as BigNumber (default) or a string
};
// If there are options, then use them to override the default _options
if (options !== undefined && options !== null) {
if (options.strict === true) {
_options.strict = true;
}
if (options.storeAsString === true) {
_options.storeAsString = true;
}
}
var at, // The index of the current character
ch, // The current character
escapee = {
'"': '"',
'\\': '\\',
'/': '/',
b: '\b',
f: '\f',
n: '\n',
r: '\r',
t: '\t'
},
text,
error = function (m) {
// Call error when something is wrong.
throw {
name: 'SyntaxError',
message: m,
at: at,
text: text
};
},
next = function (c) {
// If a c parameter is provided, verify that it matches the current character.
if (c && c !== ch) {
error("Expected '" + c + "' instead of '" + ch + "'");
}
// Get the next character. When there are no more characters,
// return the empty string.
ch = text.charAt(at);
at += 1;
return ch;
},
number = function () {
// Parse a number value.
var number,
string = '';
if (ch === '-') {
string = '-';
next('-');
}
while (ch >= '0' && ch <= '9') {
string += ch;
next();
}
if (ch === '.') {
string += '.';
while (next() && ch >= '0' && ch <= '9') {
string += ch;
}
}
if (ch === 'e' || ch === 'E') {
string += ch;
next();
if (ch === '-' || ch === '+') {
string += ch;
next();
}
while (ch >= '0' && ch <= '9') {
string += ch;
next();
}
}
number = +string;
if (!isFinite(number)) {
error("Bad number");
} else {
if (BigNumber == null)
BigNumber = require('bignumber.js');
//if (number > 9007199254740992 || number < -9007199254740992)
// Bignumber has stricter check: everything with length > 15 digits disallowed
if (string.length > 15)
return (_options.storeAsString === true) ? string : new BigNumber(string);
return number;
}
},
string = function () {
// Parse a string value.
var hex,
i,
string = '',
uffff;
// When parsing for string values, we must look for " and \ characters.
if (ch === '"') {
while (next()) {
if (ch === '"') {
next();
return string;
}
if (ch === '\\') {
next();
if (ch === 'u') {
uffff = 0;
for (i = 0; i < 4; i += 1) {
hex = parseInt(next(), 16);
if (!isFinite(hex)) {
break;
}
uffff = uffff * 16 + hex;
}
string += String.fromCharCode(uffff);
} else if (typeof escapee[ch] === 'string') {
string += escapee[ch];
} else {
break;
}
} else {
string += ch;
}
}
}
error("Bad string");
},
white = function () {
// Skip whitespace.
while (ch && ch <= ' ') {
next();
}
},
word = function () {
// true, false, or null.
switch (ch) {
case 't':
next('t');
next('r');
next('u');
next('e');
return true;
case 'f':
next('f');
next('a');
next('l');
next('s');
next('e');
return false;
case 'n':
next('n');
next('u');
next('l');
next('l');
return null;
}
error("Unexpected '" + ch + "'");
},
value, // Place holder for the value function.
array = function () {
// Parse an array value.
var array = [];
if (ch === '[') {
next('[');
white();
if (ch === ']') {
next(']');
return array; // empty array
}
while (ch) {
array.push(value());
white();
if (ch === ']') {
next(']');
return array;
}
next(',');
white();
}
}
error("Bad array");
},
object = function () {
// Parse an object value.
var key,
object = {};
if (ch === '{') {
next('{');
white();
if (ch === '}') {
next('}');
return object; // empty object
}
while (ch) {
key = string();
white();
next(':');
if (_options.strict === true && Object.hasOwnProperty.call(object, key)) {
error('Duplicate key "' + key + '"');
}
object[key] = value();
white();
if (ch === '}') {
next('}');
return object;
}
next(',');
white();
}
}
error("Bad object");
};
value = function () {
// Parse a JSON value. It could be an object, an array, a string, a number,
// or a word.
white();
switch (ch) {
case '{':
return object();
case '[':
return array();
case '"':
return string();
case '-':
return number();
default:
return ch >= '0' && ch <= '9' ? number() : word();
}
};
// Return the json_parse function. It will have access to all of the above
// functions and variables.
return function (source, reviver) {
var result;
text = source + '';
at = 0;
ch = ' ';
result = value();
white();
if (ch) {
error("Syntax error");
}
// If there is a reviver function, we recursively walk the new structure,
// passing each name/value pair to the reviver function for possible
// transformation, starting with a temporary root object that holds the result
// in an empty key. If there is not a reviver function, we simply return the
// result.
return typeof reviver === 'function'
? (function walk(holder, key) {
var k, v, value = holder[key];
if (value && typeof value === 'object') {
Object.keys(value).forEach(function(k) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
});
}
return reviver.call(holder, key, value);
}({'': result}, ''))
: result;
};
}
module.exports = json_parse;
... ...
var BigNumber = require('bignumber.js');
/*
json2.js
2013-05-26
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or '&nbsp;'),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
var JSON = module.exports;
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key],
isBigNumber = value != null && (value instanceof BigNumber || value.isBigNumber);;
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
if (isBigNumber) {
return value;
} else {
return quote(value);
}
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
Object.keys(value).forEach(function(k) {
var v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
});
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
}());
... ...
{
"_args": [
[
{
"raw": "json-bigint@^0.2.3",
"scope": null,
"escapedName": "json-bigint",
"name": "json-bigint",
"rawSpec": "^0.2.3",
"spec": ">=0.2.3 <0.3.0",
"type": "range"
},
"/Users/fzy/project/koa2_Sequelize_project/node_modules/@alicloud/pop-core"
]
],
"_from": "json-bigint@>=0.2.3 <0.3.0",
"_id": "json-bigint@0.2.3",
"_inCache": true,
"_location": "/json-bigint",
"_nodeVersion": "6.9.1",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/json-bigint-0.2.3.tgz_1484003726024_0.7127540863584727"
},
"_npmUser": {
"name": "sidorares",
"email": "sidorares@yandex.com"
},
"_npmVersion": "3.10.8",
"_phantomChildren": {},
"_requested": {
"raw": "json-bigint@^0.2.3",
"scope": null,
"escapedName": "json-bigint",
"name": "json-bigint",
"rawSpec": "^0.2.3",
"spec": ">=0.2.3 <0.3.0",
"type": "range"
},
"_requiredBy": [
"/@alicloud/pop-core"
],
"_resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-0.2.3.tgz",
"_shasum": "118d7f6ff1d38659f19f94cf73e64a75a3f988a8",
"_shrinkwrap": null,
"_spec": "json-bigint@^0.2.3",
"_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/@alicloud/pop-core",
"author": {
"name": "Andrey Sidorov",
"email": "sidorares@yandex.ru"
},
"bugs": {
"url": "https://github.com/sidorares/json-bigint/issues"
},
"dependencies": {
"bignumber.js": "^4.0.0"
},
"description": "JSON.parse with bigints support",
"devDependencies": {
"chai": "~1.9.1",
"mocha": "~1.20.1"
},
"directories": {},
"dist": {
"shasum": "118d7f6ff1d38659f19f94cf73e64a75a3f988a8",
"tarball": "https://registry.npmjs.org/json-bigint/-/json-bigint-0.2.3.tgz"
},
"gitHead": "7c3dbc180df56d329578b040bf5bedda6769ab63",
"homepage": "https://github.com/sidorares/json-bigint#readme",
"keywords": [
"JSON",
"bigint",
"bignumber",
"parse",
"json"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"name": "sidorares",
"email": "sidorares@yandex.com"
}
],
"name": "json-bigint",
"optionalDependencies": {},
"readme": "json-bigint\n===========\n\n[![Build Status](https://secure.travis-ci.org/sidorares/json-bigint.png)](http://travis-ci.org/sidorares/json-bigint)\n[![NPM](https://nodei.co/npm/json-bigint.png?downloads=true&stars=true)](https://nodei.co/npm/json-bigint/)\n\nJSON.parse/stringify with bigints support. Based on Douglas Crockford [JSON.js](https://github.com/douglascrockford/JSON-js) package and [bignumber.js](https://github.com/MikeMcl/bignumber.js) library.\n\nWhile most JSON parsers assume numeric values have same precision restrictions as IEEE 754 double, JSON specification _does not_ say anything about number precision. Any floating point number in decimal (optionally scientific) notation is valid JSON value. It's a good idea to serialize values which might fall out of IEEE 754 integer precision as strings in your JSON api, but `{ \"value\" : 9223372036854775807}`, for example, is still a valid RFC4627 JSON string, and in most JS runtimes the result of `JSON.parse` is this object: `{ value: 9223372036854776000 }`\n\n==========\n\nexample:\n\n```js\nvar JSONbig = require('json-bigint');\n\nvar json = '{ \"value\" : 9223372036854775807, \"v2\": 123 }';\nconsole.log('Input:', json);\nconsole.log('');\n\nconsole.log('node.js bult-in JSON:')\nvar r = JSON.parse(json);\nconsole.log('JSON.parse(input).value : ', r.value.toString());\nconsole.log('JSON.stringify(JSON.parse(input)):', JSON.stringify(r));\n\nconsole.log('\\n\\nbig number JSON:');\nvar r1 = JSONbig.parse(json);\nconsole.log('JSON.parse(input).value : ', r1.value.toString());\nconsole.log('JSON.stringify(JSON.parse(input)):', JSONbig.stringify(r1));\n```\n\nOutput:\n\n```\nInput: { \"value\" : 9223372036854775807, \"v2\": 123 }\n\nnode.js bult-in JSON:\nJSON.parse(input).value : 9223372036854776000\nJSON.stringify(JSON.parse(input)): {\"value\":9223372036854776000,\"v2\":123}\n\n\nbig number JSON:\nJSON.parse(input).value : 9223372036854775807\nJSON.stringify(JSON.parse(input)): {\"value\":9223372036854775807,\"v2\":123}\n```\n### Options\nThe behaviour of the parser is somewhat configurable through 'options'\n\n#### options.strict, boolean, default false\nSpecifies the parsing should be \"strict\" towards reporting duplicate-keys in the parsed string.\nThe default follows what is allowed in standard json and resembles the behavior of JSON.parse, but overwrites any previous values with the last one assigned to the duplicate-key.\n\nSetting options.strict = true will fail-fast on such duplicate-key occurances and thus warn you upfront of possible lost information.\n\nexample:\n```js\nvar JSONbig = require('json-bigint');\nvar JSONstrict = require('json-bigint')({\"strict\": true});\n\nvar dupkeys = '{ \"dupkey\": \"value 1\", \"dupkey\": \"value 2\"}';\nconsole.log('\\n\\nDuplicate Key test with both lenient and strict JSON parsing');\nconsole.log('Input:', dupkeys);\nvar works = JSONbig.parse(dupkeys);\nconsole.log('JSON.parse(dupkeys).dupkey: %s', works.dupkey);\nvar fails = \"will stay like this\";\ntry {\n fails = JSONstrict.parse(dupkeys);\n console.log('ERROR!! Should never get here');\n} catch (e) {\n console.log('Succesfully catched expected exception on duplicate keys: %j', e);\n}\n```\n\nOutput\n```\nDuplicate Key test with big number JSON\nInput: { \"dupkey\": \"value 1\", \"dupkey\": \"value 2\"}\nJSON.parse(dupkeys).dupkey: value 2\nSuccesfully catched expected exception on duplicate keys: {\"name\":\"SyntaxError\",\"message\":\"Duplicate key \\\"dupkey\\\"\",\"at\":33,\"text\":\"{ \\\"dupkey\\\": \\\"value 1\\\", \\\"dupkey\\\": \\\"value 2\\\"}\"}\n\n```\n\n#### options.storeAsString, boolean, default false\nSpecifies if BigInts should be stored in the object as a string, rather than the default BigNumber.\n\nNote that this is a dangerous behavior as it breaks the default functionality of being able to convert back-and-forth without data type changes (as this will convert all BigInts to be-and-stay strings).\n\nexample:\n```js\nvar JSONbig = require('json-bigint');\nvar JSONbigString = require('json-bigint')({\"storeAsString\": true});\nvar key = '{ \"key\": 1234567890123456789 }';\nconsole.log('\\n\\nStoring the BigInt as a string, instead of a BigNumber');\nconsole.log('Input:', key);\nvar withInt = JSONbig.parse(key);\nvar withString = JSONbigString.parse(key);\nconsole.log('Default type: %s, With option type: %s', typeof withInt.key, typeof withString.key);\n\n```\n\nOutput\n```\nStoring the BigInt as a string, instead of a BigNumber\nInput: { \"key\": 1234567890123456789 }\nDefault type: object, With option type: string\n\n```\n\n\n### Links:\n- [RFC4627: The application/json Media Type for JavaScript Object Notation (JSON)](http://www.ietf.org/rfc/rfc4627.txt)\n- [Re: \\[Json\\] Limitations on number size?](http://www.ietf.org/mail-archive/web/json/current/msg00297.html)\n- [Is there any proper way to parse JSON with large numbers? (long, bigint, int64)](http://stackoverflow.com/questions/18755125/node-js-is-there-any-proper-way-to-parse-json-with-large-numbers-long-bigint)\n- [What is JavaScript's Max Int? What's the highest Integer value a Number can go to without losing precision?](http://stackoverflow.com/questions/307179/what-is-javascripts-max-int-whats-the-highest-integer-value-a-number-can-go-t)\n- [Large numbers erroneously rounded in Javascript](http://stackoverflow.com/questions/1379934/large-numbers-erroneously-rounded-in-javascript)\n\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/sidorares/json-bigint.git"
},
"scripts": {
"test": "./node_modules/mocha/bin/mocha -R spec --check-leaks test/*-test.js"
},
"version": "0.2.3"
}
... ...
var mocha = require('mocha')
, assert = require('chai').assert
, expect = require('chai').expect
, BigNumber = require('bignumber.js')
;
describe("Testing bigint support", function(){
var input = '{"big":9223372036854775807,"small":123}';
it("Should show classic JSON.parse lacks bigint support", function(done){
var obj = JSON.parse(input);
expect(obj.small.toString(), "string from small int").to.equal("123");
expect(obj.big.toString(), "string from big int").to.not.equal("9223372036854775807");
var output = JSON.stringify(obj);
expect(output).to.not.equal(input);
done();
});
it("Should show JSNbig does support bigint parse/stringify roundtrip", function(done){
var JSONbig = require('../index');
var obj = JSONbig.parse(input);
expect(obj.small.toString(), "string from small int").to.equal("123");
expect(obj.big.toString(), "string from big int").to.equal("9223372036854775807");
expect(obj.big, "instanceof big int").to.be.instanceof(BigNumber);
var output = JSONbig.stringify(obj);
expect(output).to.equal(input);
done();
});
});
... ...
var mocha = require('mocha')
, assert = require('chai').assert
, expect = require('chai').expect
;
describe("Testing 'strict' option", function(){
var dupkeys = '{ "dupkey": "value 1", "dupkey": "value 2"}';
it("Should show that duplicate keys just get overwritten by default", function(done){
var JSONbig = require('../index');
var result = "before";
function tryParse() {
result = JSONbig.parse(dupkeys);
}
expect(tryParse).to.not.throw("anything");
expect(result.dupkey).to.equal("value 2");
done();
});
it("Should show that the 'strict' option will fail-fast on duplicate keys", function(done){
var JSONstrict = require('../index')({"strict": true});
var result = "before";
function tryParse() {
result = JSONstrict.parse(dupkeys);
}
expect(tryParse).to.throw({
name: 'SyntaxError',
message: 'Duplicate key "dupkey"',
at: 33,
text: '{ "dupkey": "value 1", "dupkey": "value 2"}'
});
expect(result).to.equal("before");
done();
});
});
... ...
var mocha = require('mocha')
, assert = require('chai').assert
, expect = require('chai').expect
;
describe("Testing 'storeAsString' option", function(){
var key = '{ "key": 12345678901234567 }';
it("Should show that the key is of type object", function(done){
var JSONbig = require('../index');
var result = JSONbig.parse(key);
expect(typeof result.key).to.equal("object");
done();
});
it("Should show that key is of type string, when storeAsString option is true", function(done){
var JSONstring = require('../index')({"storeAsString": true});
var result = JSONstring.parse(key);
expect(typeof result.key).to.equal("string");
done();
});
});
... ...
The MIT License (MIT)
Copyright (c) 2016 Jackson Tian
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
... ...
# kitx
A Node.js toolkit.
[![NPM version][npm-image]][npm-url]
[![build status][travis-image]][travis-url]
[![Coverage Status](https://coveralls.io/repos/JacksonTian/kitx/badge.svg?branch=master&service=github)](https://coveralls.io/github/JacksonTian/kitx?branch=master)
[![David deps][david-image]][david-url]
[![npm download][download-image]][download-url]
[npm-image]: https://img.shields.io/npm/v/kitx.svg?style=flat-square
[npm-url]: https://npmjs.org/package/kitx
[travis-image]: https://img.shields.io/travis/JacksonTian/kitx.svg?style=flat-square
[travis-url]: https://travis-ci.org/JacksonTian/kitx
[david-image]: https://img.shields.io/david/JacksonTian/kitx.svg?style=flat-square
[david-url]: https://david-dm.org/JacksonTian/kitx
[download-image]: https://img.shields.io/npm/dm/kitx.svg?style=flat-square
[download-url]: https://npmjs.org/package/kitx
## Installation
```sh
$ npm install kitx --save
```
## Usage
Require it:
```js
var kit = require('kitx');
```
## API
See [API docs](http://doxmate.cool/JacksonTian/kitx/api.html).
## License
The MIT license.
... ...
'use strict';
const fs = require('fs');
const os = require('os');
const crypto = require('crypto');
/**
* Load *.json file synchronous. Don't use require('*.json')
* to load *.json files, it will cached in process.
* @param {String} filename absolute file path
* @return {Object} a parsed object
*/
exports.loadJSONSync = function (filename) {
// strip BOM
var content = fs.readFileSync(filename, 'utf8');
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
try {
return JSON.parse(content);
} catch (err) {
err.message = filename + ': ' + err.message;
throw err;
}
};
/**
* Encoding a string to Buffer safely
* @param {String} str string.
* @param {String} encoding. optional.
* @return {Buffer} encoded buffer
*/
exports.encode = function (str, encoding) {
if (typeof str !== 'string') {
str = '' + str;
}
return new Buffer(str, encoding);
};
/**
* Generate a haser with specfied algorithm
* @param {String} algorithm can be md5, etc.
* @return {Function} a haser with specfied algorithm
*/
exports.makeHasher = function (algorithm) {
return function (data, encoding) {
var shasum = crypto.createHash(algorithm);
shasum.update(data);
return shasum.digest(encoding);
};
};
exports.createHash = exports.makeHasher;
/**
* Get md5 hash digests of data
* @param {String|Buffer} data data.
* @param {String} encoding optionnal. can be 'hex', 'binary', 'base64'.
* @return {String|Buffer} if no encoding is provided, a buffer is returned.
*/
exports.md5 = exports.makeHasher('md5');
/**
* Get sha1 hash digests of data
* @param {String|Buffer} data data.
* @param {String} key the key.
* @param {String} encoding optionnal. can be 'hex', 'binary', 'base64'.
* @return {String|Buffer} if no encoding is provided, a buffer is returned.
*/
exports.createHmac = function (algorithm) {
return function (data, key, encoding) {
return crypto.createHmac(algorithm, key).update(data).digest(encoding);
};
};
/**
* Get sha1 hash digests of data
* @param {String|Buffer} data data.
* @param {String} key the key.
* @param {String} encoding optionnal. can be 'hex', 'binary', 'base64'.
* @return {String|Buffer} if no encoding is provided, a buffer is returned.
*/
exports.sha1 = exports.createHmac('sha1');
/**
* Get a random value in a range
* @param {Number} min range start.
* @param {Number} max range end.
*/
exports.random = function (min, max) {
return Math.floor(min + Math.random() * (max - min));
};
/**
* Generate a nonce string
* @return {String} a nonce string.
*/
exports.makeNonce = (function() {
var counter = 0;
var last;
const machine = os.hostname();
const pid = process.pid;
return function () {
var val = Math.floor(Math.random() * 1000000000000);
if (val === last) {
counter++;
} else {
counter = 0;
}
last = val;
var uid = `${machine}${pid}${val}${counter}`;
return exports.md5(uid, 'hex');
};
}());
/**
* Pad a number as \d\d format
* @param {Number} num a number that less than 100.
* @return {String} if number less than 10, pad with 0,
* otherwise, returns string of number.
*/
exports.pad2 = function (num) {
if (num < 10) {
return '0' + num;
}
return '' + num;
};
/**
* Pad a number as \d\d\d format
* @param {Number} num a number that less than 1000.
* @return {String} if number less than 100, pad with 0,
* otherwise, returns string of number.
*/
exports.pad3 = function (num) {
if (num < 10) {
return '00' + num;
} else if (num < 100) {
return '0' + num;
}
return '' + num;
};
/**
* Return the YYYYMMDD format of a date.
* @param {Date} date a Date object.
* @return {String} the YYYYMMDD format.
*/
exports.getYYYYMMDD = function (date) {
var YYYY = date.getFullYear();
var MM = exports.pad2(date.getMonth() + 1);
var DD = exports.pad2(date.getDate());
return '' + YYYY + MM + DD;
};
/**
* sleep a while.
* @param {Number} in milliseconds
* @return {Promise} a Promise
*/
exports.sleep = function (ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
};
/**
* Get the IPv4 address
* @return {String} the IPv4 address, or empty string
*/
exports.getIPv4 = function () {
var interfaces = os.networkInterfaces();
var keys = Object.keys(interfaces);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var addresses = interfaces[key];
for (var j = 0; j < addresses.length; j++) {
var item = addresses[j];
if (!item.internal && item.family === 'IPv4') {
return item.address;
}
}
}
// without non-internal address
return '';
};
/**
* Get the Mac address
* @return {String} the Mac address
*/
exports.getMac = function () {
var interfaces = os.networkInterfaces();
var keys = Object.keys(interfaces);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var addresses = interfaces[key];
for (var j = 0; j < addresses.length; j++) {
var item = addresses[j];
if (!item.internal && item.family === 'IPv4') {
return item.mac;
}
}
}
// without non-internal address
return '00:00:00:00:00:00';
};
... ...
{
"_args": [
[
{
"raw": "kitx@^1.2.1",
"scope": null,
"escapedName": "kitx",
"name": "kitx",
"rawSpec": "^1.2.1",
"spec": ">=1.2.1 <2.0.0",
"type": "range"
},
"/Users/fzy/project/koa2_Sequelize_project/node_modules/@alicloud/pop-core"
]
],
"_from": "kitx@>=1.2.1 <2.0.0",
"_id": "kitx@1.3.0",
"_inCache": true,
"_location": "/kitx",
"_nodeVersion": "8.4.0",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/kitx-1.3.0.tgz_1505918631177_0.661639561643824"
},
"_npmUser": {
"name": "jacksontian",
"email": "shyvo1987@gmail.com"
},
"_npmVersion": "5.3.0",
"_phantomChildren": {},
"_requested": {
"raw": "kitx@^1.2.1",
"scope": null,
"escapedName": "kitx",
"name": "kitx",
"rawSpec": "^1.2.1",
"spec": ">=1.2.1 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/@alicloud/mns",
"/@alicloud/pop-core"
],
"_resolved": "https://registry.npmjs.org/kitx/-/kitx-1.3.0.tgz",
"_shasum": "ab3ee7c598d2b1d629fd55568f868c4440c200ea",
"_shrinkwrap": null,
"_spec": "kitx@^1.2.1",
"_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/@alicloud/pop-core",
"author": {
"name": "Jackson Tian"
},
"bugs": {
"url": "https://github.com/JacksonTian/kitx/issues"
},
"dependencies": {},
"description": "toolkit",
"devDependencies": {
"co-mocha": "~1.1.2",
"coveralls": "~2.11.9",
"expect.js": "~0.3.1",
"istanbul": "~0.4.2",
"mocha": "^3.4.2"
},
"directories": {
"test": "test"
},
"dist": {
"integrity": "sha512-fhBqFlXd0GkKTB+8ayLfpzPUw+LHxZlPAukPNBD1Om7JMeInT+/PxCAf1yLagvD+VKoyWhXtJR68xQkX/a0wOQ==",
"shasum": "ab3ee7c598d2b1d629fd55568f868c4440c200ea",
"tarball": "https://registry.npmjs.org/kitx/-/kitx-1.3.0.tgz"
},
"files": [
"lib"
],
"gitHead": "8c57ced8d32ad3ba7db407d5f348cfbdba777b8d",
"homepage": "https://github.com/JacksonTian/kitx#readme",
"keywords": [
"toolkit",
"kit"
],
"license": "MIT",
"main": "lib/index.js",
"maintainers": [
{
"name": "jacksontian",
"email": "shyvo1987@gmail.com"
}
],
"name": "kitx",
"optionalDependencies": {},
"readme": "# kitx\nA Node.js toolkit.\n\n[![NPM version][npm-image]][npm-url]\n[![build status][travis-image]][travis-url]\n[![Coverage Status](https://coveralls.io/repos/JacksonTian/kitx/badge.svg?branch=master&service=github)](https://coveralls.io/github/JacksonTian/kitx?branch=master)\n[![David deps][david-image]][david-url]\n[![npm download][download-image]][download-url]\n\n[npm-image]: https://img.shields.io/npm/v/kitx.svg?style=flat-square\n[npm-url]: https://npmjs.org/package/kitx\n[travis-image]: https://img.shields.io/travis/JacksonTian/kitx.svg?style=flat-square\n[travis-url]: https://travis-ci.org/JacksonTian/kitx\n[david-image]: https://img.shields.io/david/JacksonTian/kitx.svg?style=flat-square\n[david-url]: https://david-dm.org/JacksonTian/kitx\n[download-image]: https://img.shields.io/npm/dm/kitx.svg?style=flat-square\n[download-url]: https://npmjs.org/package/kitx\n\n## Installation\n\n```sh\n$ npm install kitx --save\n```\n\n## Usage\n\nRequire it:\n\n```js\nvar kit = require('kitx');\n```\n\n## API\nSee [API docs](http://doxmate.cool/JacksonTian/kitx/api.html).\n\n## License\nThe MIT license.\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+https://github.com/JacksonTian/kitx.git"
},
"scripts": {
"test": "make test"
},
"version": "1.3.0"
}
... ...
... ... @@ -9,6 +9,7 @@
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"@alicloud/sms-sdk": "^1.0.2",
"co-busboy": "^1.3.1",
"debug": "^2.6.3",
"filepreview": "^1.0.14",
... ...
const router = require('koa-router')()
var status = require('../util/resTemplate')
const emailUtil = require('../util/emailUtil')
const sendMessageUtil = require('../util/sendMessageUtil')
router.prefix('/email')
... ... @@ -19,5 +20,18 @@ router.post('/sendEmail', async (ctx, next) => {
status.catchError(ctx,400,e.message);
}
})
router.post('/sendMessage', async (ctx, next) => {
try{
var body = ctx.request.body;
let back = await sendMessageUtil.sendMessage(body.Email,null, body.userName+body.phone+body.company+body.landline+body.ip)
ctx.response.status= 200;
ctx.response.body= {
msg:'发送成功'
};
}catch(e){
console.error(e)
status.catchError(ctx,400,e.message);
}
})
module.exports = router;
\ No newline at end of file
module.exports = router;
\ No newline at end of file
... ...
... ... @@ -53,16 +53,18 @@ recordInfoService.prototype.getRecordFileURL = async(path,time)=>{
var backFile=[];
var fileU
let addrecord = await recordInfo.findAll({where:{channel:path}});
console.log('录制文件',addrecord)
let noFile = [];
var allFile = [];
let date1 = ''
var channefiles = '';
addrecord.forEach(function(record,top){
let date1 = moment(Number( record.createTime)).format('YYYYMMDD')
let date2 = moment(Number(record.createTime)-8*60*60*1000).format('YYYYMMDDhhmmss')
let channeFile = onlinePath+date1;
var fschannefiles=fs.readdirSync(channeFile);
if(top == 0){
date1 = moment(Number( record.createTime)).format('YYYYMMDD')
}
console.log(top)
fschannefiles.forEach(function(cfile,index){
if(record.channel == cfile.split('_')[0]+'_'+cfile.split("_")[1]){
let pathURL = onlinePath+date1+"/"+cfile;
... ...
/**
* 发送短信
*/
const SMSClient = require('@alicloud/sms-sdk')
// ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换
const accessKeyId = 'yourAccessKeyId'
const secretAccessKey = 'yourAccessKeySecret'
//初始化sms_client
let smsClient = new SMSClient({accessKeyId, secretAccessKey})
function message(){
}
message.prototype.sendMessage = async(recipient, subject, html) => {
try {
let smsData = await smsClient.sendSMS({
PhoneNumbers: '15314352870',
SignName: '云通信产品',
TemplateCode: 'SMS_000000',
TemplateParam: '{"code":"12345","product":"云通信"}'
})
console.log(smsData);
} catch (error) {
throw error
}
}
module.exports = new message();
\ No newline at end of file
... ...