付智勇

no message

正在显示 57 个修改的文件 包含 4288 行增加1 行删除

要显示太多修改。

为保证性能只显示 57 of 57+ 个文件。

module.exports = {
uploade:'/Users/fzy/project/koa2_Sequelize_project/uploads/'
uploade:'/Users/fzy/project/koa2_Sequelize_project/uploads/' ///Users/fzy/project/koa2_Sequelize_project/uploads/
}
\ No newline at end of file
... ...
var Sequelize = require('sequelize');
//数据配置
var sequelize = new Sequelize('saas_3m', 'test_read', "test_read7", {
// var sequelize = new Sequelize('xuedianyun', 'root', "", {
//host:'localhost',
host:'rds9vo3ja79e62m0433jo.mysql.rds.aliyuncs.com',
dialect: 'mysql',
pool: {
max: 10,
min: 0,
idle: 1000
}
})
module.exports = sequelize
\ No newline at end of file
... ...
var sequelize = require('../config');
var Sequelize = require('sequelize');
var uuid = require('../util/UuidUtil')
var recordInfo = sequelize.define('3m_record_info', {
id: {
type: Sequelize.STRING(32),
defaultValue:uuid.db32(),
allowNull: false,
unique: true,
primaryKey: true,
field: "id"
},
appId: {
allowNull: false,
type:Sequelize.STRING(50),
field: "app_id"
},
channel: {
allowNull: false,
type:Sequelize.STRING(50),
field: "channel"
},
channelKey:{
type:Sequelize.STRING(50),
field: "channel_key"
},
uid:{
type:Sequelize.STRING(50),
field: "uid"
},
userId:{
type:Sequelize.STRING(50),
field: "user_id"
},
userRole:{
type:Sequelize.STRING(50),
field: "user_role"
},
userName:{
type:Sequelize.STRING(50),
field: "user_name"
},
timestamp:{
type:Sequelize.STRING(50),
field: "timestamp"
},
recordTimestamp:{
type:Sequelize.STRING(50),
field: "recordTimestamp"
},
createTime:{
type:Sequelize.STRING(50),
field: "create_time"
},
status:{
type:Sequelize.INTEGER(1),
field:'status',
},
type:{
type:Sequelize.INTEGER(1),
field:'type',
}
}, {
timestamps: false,
freezeTableName: true
});
module.exports = recordInfo;
\ No newline at end of file
... ...
var sequelize = require('../config');
var Sequelize = require('sequelize');
var uuid = require('../util/UuidUtil')
var recordStatus = sequelize.define('3m_record_status', {
id: {
type: Sequelize.STRING(32),
defaultValue:uuid.db32(),
allowNull: false,
unique: true,
primaryKey: true,
field: "id"
},
channel:{
type:Sequelize.STRING(50),
field: "channel"
},
status:{
type:Sequelize.INTEGER(1),
field:'status',
},
}, {
timestamps: false,
freezeTableName: true
});
module.exports = recordStatus;
\ No newline at end of file
... ...
var sequelize = require('../config');
var Sequelize = require('sequelize');
const uuid = require('../util/UuidUtil')
var site = sequelize.define('3m_site', {
id: {
type: Sequelize.STRING(32),
defaultValue:uuid.db32(),
allowNull: false,
unique: true,
primaryKey: true,
field: "id"
},
siteId: {
type:Sequelize.STRING(32),
field: "siteid"
},
siteKey: {
type:Sequelize.STRING(128),
field: "site_key"
},
startDate:{
type:Sequelize.TEXT(0),
field: "startdate"
},
endDate:{
type:Sequelize.STRING(1024),
field: "enddate"
},
aseKey:{
type:Sequelize.STRING(128),
field: "ase_key"
},
mcuList:{
type:Sequelize.INTEGER(1),
field: "mcu_list"
},
msList:{
type:Sequelize.INTEGER(1),
field: "ms_list"
},
rsList:{
type:Sequelize.INTEGER(1),
field: "rs_list"
},
docList:{
type:Sequelize.STRING(32),
field: "doc_list"
}
}, {
timestamps: false,
freezeTableName: true
});
module.exports = site;
\ No newline at end of file
... ...
var sequelize = require('../config');
var Sequelize = require('sequelize');
const uuid = require('../util/UuidUtil')
var studentMeeting = sequelize.define('3m_student_meeting', {
id: {
type: Sequelize.STRING(32),
defaultValue:uuid.db32(),
allowNull: false,
unique: true,
primaryKey: true,
field: "id"
},
studentId: {
allowNull: false,
type:Sequelize.STRING(32),
field: "student_id"
},
meetingId: {
allowNull: false,
type:Sequelize.STRING(32),
field: "meeting_id"
},
siteId: {
allowNull: false,
type:Sequelize.STRING(32),
field: "site_id"
},
status: {
allowNull: false,
type:Sequelize.STRING(32),
field: "status"
},
createTime: {
allowNull: false,
type:Sequelize.STRING(32),
field: "create_time"
}
},{
timestamps: false,
freezeTableName: true
});
module.exports = studentMeeting;
\ No newline at end of file
... ...
var sequelize = require('../config');
var Sequelize = require('sequelize');
var uuid = require('../util/UuidUtil')
var user = sequelize.define('3m_user', {
id: {
type: Sequelize.STRING(32),
defaultValue:uuid.db32(),
allowNull: false,
unique: true,
primaryKey: true,
field: "id"
},
loginName: {
allowNull: false,
type:Sequelize.STRING(100),
field: "login_name"
},
// IDcard: {
// allowNull: false,
// type:Sequelize.STRING(50),
// field: "IDcard"
// },
password: {
allowNull: false,
type:Sequelize.STRING(100),
field: "password"
},
// salt:{
// type:Sequelize.INTEGER(2),
// field: "salt"
// },
companyName:{
type:Sequelize.STRING(1024),
field: "company_name"
},
userName:{
type:Sequelize.STRING(64),
field: "user_name"
},
userType:{
type:Sequelize.INTEGER(1),
field: "user_type"
},
userRole:{
type:Sequelize.INTEGER(1),
field: "user_role"
},
userEmail:{
type:Sequelize.INTEGER(1),
field: "user_email"
},
userMobile:{
type:Sequelize.STRING(32),
field: "user_mobile"
},
createTime:{
type:Sequelize.DATE,
defaultValue:Sequelize.NOW,
field: "create_time"
},
endTime:{
type:Sequelize.DATE,
field: "end_time"
},
content:{
type:Sequelize.TEXT(1024),
field: "content"
},
serialNo:{
type:Sequelize.INTEGER(11),
field: "serial_no"
},
siteId:{
type:Sequelize.STRING(32),
field: "site_id"
},
userStatus:{
type:Sequelize.INTEGER(11),
field: "user_status"
},
groupId:{
type:Sequelize.STRING(128),
field: "group_id"
},
}, {
timestamps: false,
freezeTableName: true
});
module.exports = user;
\ No newline at end of file
... ...
var sequelize = require('../db2.config');
var Sequelize = require('sequelize');
const uuid = require('../util/UuidUtil')
var user = sequelize.define('3m_meeting', {
id: {
type: Sequelize.STRING(32),
defaultValue:uuid.db32(),
allowNull: false,
unique: true,
primaryKey: true,
field: "id"
},
meetingNumber: {
type:Sequelize.STRING(32),
field: "meeting_number"
},
meetingName: {
type:Sequelize.STRING(128),
field: "meeting_name"
},
meetingContent:{
type:Sequelize.TEXT(0),
field: "meeting_content"
},
create_user:{
type:Sequelize.STRING(128),
field: "create_user"
},
createTime:{
type:Sequelize.DATE,
defaultValue:Sequelize.NOW,
field: "create_time"
},
beginTime:{
type:Sequelize.DATE,
field: "begin_time"
},
endTime:{
type:Sequelize.DATE,
field: "end_time"
},
inviteUser:{
type:Sequelize.STRING(1024),
field: "invite_user"
},
meetingType:{
type:Sequelize.INTEGER(4),
field: "meeting_type"
},
meetingStatus:{
type:Sequelize.STRING(32),
field: "meeting_status"
},
userIp:{
type:Sequelize.INTEGER(11),
field: "user_ip"
},
meetingKey:{
type:Sequelize.STRING(128),
field: "meeting_key"
},
hostPassword:{
type:Sequelize.STRING(12),
field: "host_password"
},
presenterPassword:{
type:Sequelize.STRING(12),
field: "presenter_password"
},
assistantPassword:{
type:Sequelize.STRING(12),
field: "assistant_password"
},
attendeePassword:{
type:Sequelize.STRING(12),
field: "attendee_password"
},
capacity:{
type:Sequelize.INTEGER(11),
field: "capacity"
},
topNodeId:{
type:Sequelize.STRING(32),
field: "top_node_id"
},
topNodeAddr:{
type:Sequelize.STRING(128),
field: "top_node_addr"
},
userData:{
type:Sequelize.STRING(128),
field: "user_data"
},
siteId:{
type:Sequelize.STRING(32),
field: "site_id"
},
classroomNumber:{
type:Sequelize.STRING(128),
field: "classroom_number"
},
uiLanguage:{
type:Sequelize.INTEGER(11),
field: "ui_language"
},
isPublic:{
type:Sequelize.INTEGER(11),
field: "is_public"
},
controlMode:{
type:Sequelize.INTEGER(11),
field: "control_mode"
},
micAuto:{
type:Sequelize.INTEGER(11),
field: "mic_auto"
},
hasInteraction:{
type:Sequelize.INTEGER(11),
field: "has_interaction"
},
autoRecord:{
type:Sequelize.INTEGER(11),
field: "auto_record"
},
maxVideoChannels:{
type:Sequelize.INTEGER(11),
field: "max_videoChannels"
},
maxAudioChannels:{
type:Sequelize.INTEGER(11),
field: "max_audioChannels"
},
videoQuality:{
type:Sequelize.INTEGER(11),
field: "video_quality"
},
pagenaviUserprivilege:{
type:Sequelize.INTEGER(11),
field: "pagenavi_Userprivilege"
},
markerUserprivilege:{
type:Sequelize.INTEGER(11),
field: "marker_Userprivilege"
},
chatToNormalUserprivilege:{
type:Sequelize.INTEGER(11),
field: "chatToNormal_Userprivilege"
},
chatToHostUserprivilege:{
type:Sequelize.INTEGER(11),
field: "chatToHost_Userprivilege"
},
docModule:{
type:Sequelize.INTEGER(11),
field: "doc_module"
},
screenModule:{
type:Sequelize.INTEGER(11),
field: "screen_module"
},
mediaModule:{
type:Sequelize.INTEGER(11),
field: "media_module"
},
whiteboardModule:{
type:Sequelize.INTEGER(11),
field: "whiteboard_module"
},
recordModule:{
type:Sequelize.INTEGER(11),
field: "record_module"
},
videoModule:{
type:Sequelize.INTEGER(11),
field: "video_module"
},
userListModule:{
type:Sequelize.INTEGER(11),
field: "userList_module"
},
chatModule:{
type:Sequelize.INTEGER(11),
field: "chat_module"
},
cycle:{
type:Sequelize.INTEGER(11),
field: "cycle"
},
repeatmode:{
type:Sequelize.INTEGER(11),
field: "repeatmode"
},
endmode:{
type:Sequelize.INTEGER(11),
field: "endmode"
},
finalenddate:{
type:Sequelize.INTEGER(11),
field: "finalenddate"
},
endcount:{
type:Sequelize.INTEGER(11),
field: "endcount"
},
repeatday:{
type:Sequelize.INTEGER(11),
field: "repeatday"
},
repeatweek:{
type:Sequelize.INTEGER(11),
field: "repeatweek"
},
repeatmonthday:{
type:Sequelize.INTEGER(11),
field: "repeatmonthday"
},
repeatmonthweekweek:{
type:Sequelize.INTEGER(11),
field: "repeatmonthweekweek"
},
repeatmonthweekday:{
type:Sequelize.INTEGER(11),
field: "repeatmonthweekday"
},
frequency:{
type:Sequelize.INTEGER(11),
field: "frequency"
},
monthType:{
type:Sequelize.INTEGER(11),
field: "month_type"
},
inviterRadio:{
type:Sequelize.INTEGER(11),
field: "inviter_radio"
},
aheadTime:{
type:Sequelize.INTEGER(11),
field: "ahead_time"
},
chatInterval:{
type:Sequelize.INTEGER(11),
field: "chat_interval"
},
h5Module:{
type:Sequelize.INTEGER(11),
field: "h5_Module"
},
// reservationNumber:{
// type:Sequelize.INTEGER(11),
// field: "reservation_number"
// },
}, {
timestamps: false,
freezeTableName: true
});
module.exports = user;
\ No newline at end of file
... ...
../node-gyp/bin/node-gyp.js
\ No newline at end of file
... ...
../rimraf/bin.js
\ No newline at end of file
... ...
Copyright (c) 2015, Rebecca Turner <me@re-becca.org>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
... ...
aproba
======
A ridiculously light-weight function argument validator
```
var validate = require("aproba")
function myfunc(a, b, c) {
// `a` must be a string, `b` a number, `c` a function
validate('SNF', arguments) // [a,b,c] is also valid
}
myfunc('test', 23, function () {}) // ok
myfunc(123, 23, function () {}) // type error
myfunc('test', 23) // missing arg error
myfunc('test', 23, function () {}, true) // too many args error
```
Valid types are:
| type | description
| :--: | :----------
| * | matches any type
| A | `Array.isArray` OR an `arguments` object
| S | typeof == string
| N | typeof == number
| F | typeof == function
| O | typeof == object and not type A and not type E
| B | typeof == boolean
| E | `instanceof Error` OR `null` **(special: see below)**
| Z | == `null`
Validation failures throw one of three exception types, distinguished by a
`code` property of `EMISSINGARG`, `EINVALIDTYPE` or `ETOOMANYARGS`.
If you pass in an invalid type then it will throw with a code of
`EUNKNOWNTYPE`.
If an **error** argument is found and is not null then the remaining
arguments are optional. That is, if you say `ESO` then that's like using a
non-magical `E` in: `E|ESO|ZSO`.
### But I have optional arguments?!
You can provide more than one signature by separating them with pipes `|`.
If any signature matches the arguments then they'll be considered valid.
So for example, say you wanted to write a signature for
`fs.createWriteStream`. The docs for it describe it thusly:
```
fs.createWriteStream(path[, options])
```
This would be a signature of `SO|S`. That is, a string and and object, or
just a string.
Now, if you read the full `fs` docs, you'll see that actually path can ALSO
be a buffer. And options can be a string, that is:
```
path <String> | <Buffer>
options <String> | <Object>
```
To reproduce this you have to fully enumerate all of the possible
combinations and that implies a signature of `SO|SS|OO|OS|S|O`. The
awkwardness is a feature: It reminds you of the complexity you're adding to
your API when you do this sort of thing.
### Browser support
This has no dependencies and should work in browsers, though you'll have
noisier stack traces.
### Why this exists
I wanted a very simple argument validator. It needed to do two things:
1. Be more concise and easier to use than assertions
2. Not encourage an infinite bikeshed of DSLs
This is why types are specified by a single character and there's no such
thing as an optional argument.
This is not intended to validate user data. This is specifically about
asserting the interface of your functions.
If you need greater validation, I encourage you to write them by hand or
look elsewhere.
... ...
'use strict'
function isArguments (thingy) {
return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee')
}
var types = {
'*': {label: 'any', check: function () { return true }},
A: {label: 'array', check: function (thingy) { return Array.isArray(thingy) || isArguments(thingy) }},
S: {label: 'string', check: function (thingy) { return typeof thingy === 'string' }},
N: {label: 'number', check: function (thingy) { return typeof thingy === 'number' }},
F: {label: 'function', check: function (thingy) { return typeof thingy === 'function' }},
O: {label: 'object', check: function (thingy) { return typeof thingy === 'object' && thingy != null && !types.A.check(thingy) && !types.E.check(thingy) }},
B: {label: 'boolean', check: function (thingy) { return typeof thingy === 'boolean' }},
E: {label: 'error', check: function (thingy) { return thingy instanceof Error }},
Z: {label: 'null', check: function (thingy) { return thingy == null }}
}
function addSchema (schema, arity) {
var group = arity[schema.length] = arity[schema.length] || []
if (group.indexOf(schema) === -1) group.push(schema)
}
var validate = module.exports = function (rawSchemas, args) {
if (arguments.length !== 2) throw wrongNumberOfArgs(['SA'], arguments.length)
if (!rawSchemas) throw missingRequiredArg(0, 'rawSchemas')
if (!args) throw missingRequiredArg(1, 'args')
if (!types.S.check(rawSchemas)) throw invalidType(0, ['string'], rawSchemas)
if (!types.A.check(args)) throw invalidType(1, ['array'], args)
var schemas = rawSchemas.split('|')
var arity = {}
schemas.forEach(function (schema) {
for (var ii = 0; ii < schema.length; ++ii) {
var type = schema[ii]
if (!types[type]) throw unknownType(ii, type)
}
if (/E.*E/.test(schema)) throw moreThanOneError(schema)
addSchema(schema, arity)
if (/E/.test(schema)) {
addSchema(schema.replace(/E.*$/, 'E'), arity)
addSchema(schema.replace(/E/, 'Z'), arity)
if (schema.length === 1) addSchema('', arity)
}
})
var matching = arity[args.length]
if (!matching) {
throw wrongNumberOfArgs(Object.keys(arity), args.length)
}
for (var ii = 0; ii < args.length; ++ii) {
var newMatching = matching.filter(function (schema) {
var type = schema[ii]
var typeCheck = types[type].check
return typeCheck(args[ii])
})
if (!newMatching.length) {
var labels = matching.map(function (schema) {
return types[schema[ii]].label
}).filter(function (schema) { return schema != null })
throw invalidType(ii, labels, args[ii])
}
matching = newMatching
}
}
function missingRequiredArg (num) {
return newException('EMISSINGARG', 'Missing required argument #' + (num + 1))
}
function unknownType (num, type) {
return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1))
}
function invalidType (num, expectedTypes, value) {
var valueType
Object.keys(types).forEach(function (typeCode) {
if (types[typeCode].check(value)) valueType = types[typeCode].label
})
return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' +
englishList(expectedTypes) + ' but got ' + valueType)
}
function englishList (list) {
return list.join(', ').replace(/, ([^,]+)$/, ' or $1')
}
function wrongNumberOfArgs (expected, got) {
var english = englishList(expected)
var args = expected.every(function (ex) { return ex.length === 1 })
? 'argument'
: 'arguments'
return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got)
}
function moreThanOneError (schema) {
return newException('ETOOMANYERRORTYPES',
'Only one error type per argument signature is allowed, more than one found in "' + schema + '"')
}
function newException (code, msg) {
var e = new Error(msg)
e.code = code
if (Error.captureStackTrace) Error.captureStackTrace(e, validate)
return e
}
... ...
{
"_args": [
[
{
"raw": "aproba@^1.0.3",
"scope": null,
"escapedName": "aproba",
"name": "aproba",
"rawSpec": "^1.0.3",
"spec": ">=1.0.3 <2.0.0",
"type": "range"
},
"/Users/fzy/project/koa2_Sequelize_project/node_modules/gauge"
]
],
"_from": "aproba@>=1.0.3 <2.0.0",
"_id": "aproba@1.2.0",
"_inCache": true,
"_location": "/aproba",
"_nodeVersion": "8.5.0",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/aproba-1.2.0.tgz_1505861292502_0.3447994305752218"
},
"_npmUser": {
"name": "iarna",
"email": "me@re-becca.org"
},
"_npmVersion": "5.4.2",
"_phantomChildren": {},
"_requested": {
"raw": "aproba@^1.0.3",
"scope": null,
"escapedName": "aproba",
"name": "aproba",
"rawSpec": "^1.0.3",
"spec": ">=1.0.3 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/gauge"
],
"_resolved": "https://registry.npmjs.org/aproba/-/aproba-1.2.0.tgz",
"_shasum": "6802e6264efd18c790a1b0d517f0f2627bf2c94a",
"_shrinkwrap": null,
"_spec": "aproba@^1.0.3",
"_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/gauge",
"author": {
"name": "Rebecca Turner",
"email": "me@re-becca.org"
},
"bugs": {
"url": "https://github.com/iarna/aproba/issues"
},
"dependencies": {},
"description": "A ridiculously light-weight argument validator (now browser friendly)",
"devDependencies": {
"standard": "^10.0.3",
"tap": "^10.0.2"
},
"directories": {
"test": "test"
},
"dist": {
"integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==",
"shasum": "6802e6264efd18c790a1b0d517f0f2627bf2c94a",
"tarball": "https://registry.npmjs.org/aproba/-/aproba-1.2.0.tgz"
},
"files": [
"index.js"
],
"gitHead": "ee43ce68c9992e8f9d0d925dc2b1f2e1e5c976de",
"homepage": "https://github.com/iarna/aproba",
"keywords": [
"argument",
"validate"
],
"license": "ISC",
"main": "index.js",
"maintainers": [
{
"name": "iarna",
"email": "me@re-becca.org"
}
],
"name": "aproba",
"optionalDependencies": {},
"readme": "aproba\n======\n\nA ridiculously light-weight function argument validator\n\n```\nvar validate = require(\"aproba\")\n\nfunction myfunc(a, b, c) {\n // `a` must be a string, `b` a number, `c` a function\n validate('SNF', arguments) // [a,b,c] is also valid\n}\n\nmyfunc('test', 23, function () {}) // ok\nmyfunc(123, 23, function () {}) // type error\nmyfunc('test', 23) // missing arg error\nmyfunc('test', 23, function () {}, true) // too many args error\n\n```\n\nValid types are:\n\n| type | description\n| :--: | :----------\n| * | matches any type\n| A | `Array.isArray` OR an `arguments` object\n| S | typeof == string\n| N | typeof == number\n| F | typeof == function\n| O | typeof == object and not type A and not type E\n| B | typeof == boolean\n| E | `instanceof Error` OR `null` **(special: see below)**\n| Z | == `null`\n\nValidation failures throw one of three exception types, distinguished by a\n`code` property of `EMISSINGARG`, `EINVALIDTYPE` or `ETOOMANYARGS`.\n\nIf you pass in an invalid type then it will throw with a code of\n`EUNKNOWNTYPE`.\n\nIf an **error** argument is found and is not null then the remaining\narguments are optional. That is, if you say `ESO` then that's like using a\nnon-magical `E` in: `E|ESO|ZSO`.\n\n### But I have optional arguments?!\n\nYou can provide more than one signature by separating them with pipes `|`.\nIf any signature matches the arguments then they'll be considered valid.\n\nSo for example, say you wanted to write a signature for\n`fs.createWriteStream`. The docs for it describe it thusly:\n\n```\nfs.createWriteStream(path[, options])\n```\n\nThis would be a signature of `SO|S`. That is, a string and and object, or\njust a string.\n\nNow, if you read the full `fs` docs, you'll see that actually path can ALSO\nbe a buffer. And options can be a string, that is:\n```\npath <String> | <Buffer>\noptions <String> | <Object>\n```\n\nTo reproduce this you have to fully enumerate all of the possible\ncombinations and that implies a signature of `SO|SS|OO|OS|S|O`. The\nawkwardness is a feature: It reminds you of the complexity you're adding to\nyour API when you do this sort of thing.\n\n\n### Browser support\n\nThis has no dependencies and should work in browsers, though you'll have\nnoisier stack traces.\n\n### Why this exists\n\nI wanted a very simple argument validator. It needed to do two things:\n\n1. Be more concise and easier to use than assertions\n\n2. Not encourage an infinite bikeshed of DSLs\n\nThis is why types are specified by a single character and there's no such\nthing as an optional argument. \n\nThis is not intended to validate user data. This is specifically about\nasserting the interface of your functions.\n\nIf you need greater validation, I encourage you to write them by hand or\nlook elsewhere.\n\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+https://github.com/iarna/aproba.git"
},
"scripts": {
"test": "standard && tap -j3 test/*.js"
},
"version": "1.2.0"
}
... ...
Hi, figured we could actually use a changelog now:
## 1.1.4 2017-04-21
* Fix typo in package.json
## 1.1.3 2017-04-21
* Improve documentation and limit files included in the distribution.
## 1.1.2 2016-03-15
* Add tracker group cycle detection and tests for it
## 1.1.1 2016-01-29
* Fix a typo in stream completion tracker
## 1.1.0 2016-01-29
* Rewrote completion percent computation to be low impact– no more walking a
tree of completion groups every time we need this info. Previously, with
medium sized tree of completion groups, even a relatively modest number of
calls to the top level `completed()` method would result in absurd numbers
of calls overall as it walked down the tree. We now, instead, keep track as
we bubble up changes, so the computation is limited to when data changes and
to the depth of that one branch, instead of _every_ node. (Plus, we were already
incurring _this_ cost, since we already bubbled out changes.)
* Moved different tracker types out to their own files.
* Made tests test for TOO MANY events too.
* Standarized the source code formatting
... ...
Copyright (c) 2015, Rebecca Turner
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
... ...
are-we-there-yet
----------------
Track complex hiearchies of asynchronous task completion statuses. This is
intended to give you a way of recording and reporting the progress of the big
recursive fan-out and gather type workflows that are so common in async.
What you do with this completion data is up to you, but the most common use case is to
feed it to one of the many progress bar modules.
Most progress bar modules include a rudamentary version of this, but my
needs were more complex.
Usage
=====
```javascript
var TrackerGroup = require("are-we-there-yet").TrackerGroup
var top = new TrackerGroup("program")
var single = top.newItem("one thing", 100)
single.completeWork(20)
console.log(top.completed()) // 0.2
fs.stat("file", function(er, stat) {
if (er) throw er
var stream = top.newStream("file", stat.size)
console.log(top.completed()) // now 0.1 as single is 50% of the job and is 20% complete
// and 50% * 20% == 10%
fs.createReadStream("file").pipe(stream).on("data", function (chunk) {
// do stuff with chunk
})
top.on("change", function (name) {
// called each time a chunk is read from "file"
// top.completed() will start at 0.1 and fill up to 0.6 as the file is read
})
})
```
Shared Methods
==============
* var completed = tracker.completed()
Implemented in: `Tracker`, `TrackerGroup`, `TrackerStream`
Returns the ratio of completed work to work to be done. Range of 0 to 1.
* tracker.finish()
Implemented in: `Tracker`, `TrackerGroup`
Marks the tracker as completed. With a TrackerGroup this marks all of its
components as completed.
Marks all of the components of this tracker as finished, which in turn means
that `tracker.completed()` for this will now be 1.
This will result in one or more `change` events being emitted.
Events
======
All tracker objects emit `change` events with the following arguments:
```
function (name, completed, tracker)
```
`name` is the name of the tracker that originally emitted the event,
or if it didn't have one, the first containing tracker group that had one.
`completed` is the percent complete (as returned by `tracker.completed()` method).
`tracker` is the tracker object that you are listening for events on.
TrackerGroup
============
* var tracker = new TrackerGroup(**name**)
* **name** *(optional)* - The name of this tracker group, used in change
notifications if the component updating didn't have a name. Defaults to undefined.
Creates a new empty tracker aggregation group. These are trackers whose
completion status is determined by the completion status of other trackers.
* tracker.addUnit(**otherTracker**, **weight**)
* **otherTracker** - Any of the other are-we-there-yet tracker objects
* **weight** *(optional)* - The weight to give the tracker, defaults to 1.
Adds the **otherTracker** to this aggregation group. The weight determines
how long you expect this tracker to take to complete in proportion to other
units. So for instance, if you add one tracker with a weight of 1 and
another with a weight of 2, you're saying the second will take twice as long
to complete as the first. As such, the first will account for 33% of the
completion of this tracker and the second will account for the other 67%.
Returns **otherTracker**.
* var subGroup = tracker.newGroup(**name**, **weight**)
The above is exactly equivalent to:
```javascript
var subGroup = tracker.addUnit(new TrackerGroup(name), weight)
```
* var subItem = tracker.newItem(**name**, **todo**, **weight**)
The above is exactly equivalent to:
```javascript
var subItem = tracker.addUnit(new Tracker(name, todo), weight)
```
* var subStream = tracker.newStream(**name**, **todo**, **weight**)
The above is exactly equivalent to:
```javascript
var subStream = tracker.addUnit(new TrackerStream(name, todo), weight)
```
* console.log( tracker.debug() )
Returns a tree showing the completion of this tracker group and all of its
children, including recursively entering all of the children.
Tracker
=======
* var tracker = new Tracker(**name**, **todo**)
* **name** *(optional)* The name of this counter to report in change
events. Defaults to undefined.
* **todo** *(optional)* The amount of work todo (a number). Defaults to 0.
Ordinarily these are constructed as a part of a tracker group (via
`newItem`).
* var completed = tracker.completed()
Returns the ratio of completed work to work to be done. Range of 0 to 1. If
total work to be done is 0 then it will return 0.
* tracker.addWork(**todo**)
* **todo** A number to add to the amount of work to be done.
Increases the amount of work to be done, thus decreasing the completion
percentage. Triggers a `change` event.
* tracker.completeWork(**completed**)
* **completed** A number to add to the work complete
Increase the amount of work complete, thus increasing the completion percentage.
Will never increase the work completed past the amount of work todo. That is,
percentages > 100% are not allowed. Triggers a `change` event.
* tracker.finish()
Marks this tracker as finished, tracker.completed() will now be 1. Triggers
a `change` event.
TrackerStream
=============
* var tracker = new TrackerStream(**name**, **size**, **options**)
* **name** *(optional)* The name of this counter to report in change
events. Defaults to undefined.
* **size** *(optional)* The number of bytes being sent through this stream.
* **options** *(optional)* A hash of stream options
The tracker stream object is a pass through stream that updates an internal
tracker object each time a block passes through. It's intended to track
downloads, file extraction and other related activities. You use it by piping
your data source into it and then using it as your data source.
If your data has a length attribute then that's used as the amount of work
completed when the chunk is passed through. If it does not (eg, object
streams) then each chunk counts as completing 1 unit of work, so your size
should be the total number of objects being streamed.
* tracker.addWork(**todo**)
* **todo** Increase the expected overall size by **todo** bytes.
Increases the amount of work to be done, thus decreasing the completion
percentage. Triggers a `change` event.
... ...
'use strict'
exports.TrackerGroup = require('./tracker-group.js')
exports.Tracker = require('./tracker.js')
exports.TrackerStream = require('./tracker-stream.js')
... ...
{
"_args": [
[
{
"raw": "are-we-there-yet@~1.1.2",
"scope": null,
"escapedName": "are-we-there-yet",
"name": "are-we-there-yet",
"rawSpec": "~1.1.2",
"spec": ">=1.1.2 <1.2.0",
"type": "range"
},
"/Users/fzy/project/koa2_Sequelize_project/node_modules/npmlog"
]
],
"_from": "are-we-there-yet@>=1.1.2 <1.2.0",
"_id": "are-we-there-yet@1.1.4",
"_inCache": true,
"_location": "/are-we-there-yet",
"_nodeVersion": "7.7.4",
"_npmOperationalInternal": {
"host": "packages-18-east.internal.npmjs.com",
"tmp": "tmp/are-we-there-yet-1.1.4.tgz_1492760790532_0.2543606413528323"
},
"_npmUser": {
"name": "iarna",
"email": "me@re-becca.org"
},
"_npmVersion": "4.5.0",
"_phantomChildren": {},
"_requested": {
"raw": "are-we-there-yet@~1.1.2",
"scope": null,
"escapedName": "are-we-there-yet",
"name": "are-we-there-yet",
"rawSpec": "~1.1.2",
"spec": ">=1.1.2 <1.2.0",
"type": "range"
},
"_requiredBy": [
"/npmlog"
],
"_resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-1.1.4.tgz",
"_shasum": "bb5dca382bb94f05e15194373d16fd3ba1ca110d",
"_shrinkwrap": null,
"_spec": "are-we-there-yet@~1.1.2",
"_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/npmlog",
"author": {
"name": "Rebecca Turner",
"url": "http://re-becca.org"
},
"bugs": {
"url": "https://github.com/iarna/are-we-there-yet/issues"
},
"dependencies": {
"delegates": "^1.0.0",
"readable-stream": "^2.0.6"
},
"description": "Keep track of the overall completion of many disparate processes",
"devDependencies": {
"standard": "^6.0.8",
"tap": "^5.7.0"
},
"directories": {},
"dist": {
"shasum": "bb5dca382bb94f05e15194373d16fd3ba1ca110d",
"tarball": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-1.1.4.tgz"
},
"files": [
"index.js",
"tracker-base.js",
"tracker-group.js",
"tracker-stream.js",
"tracker.js",
"CHANGES.md"
],
"gitHead": "aea89b9c277c0674a2485a3eb94a7269bb2346be",
"homepage": "https://github.com/iarna/are-we-there-yet",
"license": "ISC",
"main": "index.js",
"maintainers": [
{
"name": "iarna",
"email": "me@re-becca.org"
}
],
"name": "are-we-there-yet",
"optionalDependencies": {},
"readme": "are-we-there-yet\n----------------\n\nTrack complex hiearchies of asynchronous task completion statuses. This is\nintended to give you a way of recording and reporting the progress of the big\nrecursive fan-out and gather type workflows that are so common in async.\n\nWhat you do with this completion data is up to you, but the most common use case is to\nfeed it to one of the many progress bar modules.\n\nMost progress bar modules include a rudamentary version of this, but my\nneeds were more complex.\n\nUsage\n=====\n\n```javascript\nvar TrackerGroup = require(\"are-we-there-yet\").TrackerGroup\n\nvar top = new TrackerGroup(\"program\")\n\nvar single = top.newItem(\"one thing\", 100)\nsingle.completeWork(20)\n\nconsole.log(top.completed()) // 0.2\n\nfs.stat(\"file\", function(er, stat) {\n if (er) throw er \n var stream = top.newStream(\"file\", stat.size)\n console.log(top.completed()) // now 0.1 as single is 50% of the job and is 20% complete\n // and 50% * 20% == 10%\n fs.createReadStream(\"file\").pipe(stream).on(\"data\", function (chunk) {\n // do stuff with chunk\n })\n top.on(\"change\", function (name) {\n // called each time a chunk is read from \"file\"\n // top.completed() will start at 0.1 and fill up to 0.6 as the file is read\n })\n})\n```\n\nShared Methods\n==============\n\n* var completed = tracker.completed()\n\nImplemented in: `Tracker`, `TrackerGroup`, `TrackerStream`\n\nReturns the ratio of completed work to work to be done. Range of 0 to 1.\n\n* tracker.finish()\n\nImplemented in: `Tracker`, `TrackerGroup`\n\nMarks the tracker as completed. With a TrackerGroup this marks all of its\ncomponents as completed.\n\nMarks all of the components of this tracker as finished, which in turn means\nthat `tracker.completed()` for this will now be 1.\n\nThis will result in one or more `change` events being emitted.\n\nEvents\n======\n\nAll tracker objects emit `change` events with the following arguments:\n\n```\nfunction (name, completed, tracker)\n```\n\n`name` is the name of the tracker that originally emitted the event,\nor if it didn't have one, the first containing tracker group that had one.\n\n`completed` is the percent complete (as returned by `tracker.completed()` method).\n\n`tracker` is the tracker object that you are listening for events on.\n\nTrackerGroup\n============\n\n* var tracker = new TrackerGroup(**name**)\n\n * **name** *(optional)* - The name of this tracker group, used in change\n notifications if the component updating didn't have a name. Defaults to undefined.\n\nCreates a new empty tracker aggregation group. These are trackers whose\ncompletion status is determined by the completion status of other trackers.\n\n* tracker.addUnit(**otherTracker**, **weight**)\n\n * **otherTracker** - Any of the other are-we-there-yet tracker objects\n * **weight** *(optional)* - The weight to give the tracker, defaults to 1.\n\nAdds the **otherTracker** to this aggregation group. The weight determines\nhow long you expect this tracker to take to complete in proportion to other\nunits. So for instance, if you add one tracker with a weight of 1 and\nanother with a weight of 2, you're saying the second will take twice as long\nto complete as the first. As such, the first will account for 33% of the\ncompletion of this tracker and the second will account for the other 67%.\n\nReturns **otherTracker**.\n\n* var subGroup = tracker.newGroup(**name**, **weight**)\n\nThe above is exactly equivalent to:\n\n```javascript\n var subGroup = tracker.addUnit(new TrackerGroup(name), weight)\n```\n\n* var subItem = tracker.newItem(**name**, **todo**, **weight**)\n\nThe above is exactly equivalent to:\n\n```javascript\n var subItem = tracker.addUnit(new Tracker(name, todo), weight)\n```\n\n* var subStream = tracker.newStream(**name**, **todo**, **weight**)\n\nThe above is exactly equivalent to:\n\n```javascript\n var subStream = tracker.addUnit(new TrackerStream(name, todo), weight)\n```\n\n* console.log( tracker.debug() )\n\nReturns a tree showing the completion of this tracker group and all of its\nchildren, including recursively entering all of the children.\n\nTracker\n=======\n\n* var tracker = new Tracker(**name**, **todo**)\n\n * **name** *(optional)* The name of this counter to report in change\n events. Defaults to undefined.\n * **todo** *(optional)* The amount of work todo (a number). Defaults to 0.\n\nOrdinarily these are constructed as a part of a tracker group (via\n`newItem`).\n\n* var completed = tracker.completed()\n\nReturns the ratio of completed work to work to be done. Range of 0 to 1. If\ntotal work to be done is 0 then it will return 0.\n\n* tracker.addWork(**todo**)\n\n * **todo** A number to add to the amount of work to be done.\n\nIncreases the amount of work to be done, thus decreasing the completion\npercentage. Triggers a `change` event.\n\n* tracker.completeWork(**completed**)\n\n * **completed** A number to add to the work complete\n\nIncrease the amount of work complete, thus increasing the completion percentage.\nWill never increase the work completed past the amount of work todo. That is,\npercentages > 100% are not allowed. Triggers a `change` event.\n\n* tracker.finish()\n\nMarks this tracker as finished, tracker.completed() will now be 1. Triggers\na `change` event.\n\nTrackerStream\n=============\n\n* var tracker = new TrackerStream(**name**, **size**, **options**)\n\n * **name** *(optional)* The name of this counter to report in change\n events. Defaults to undefined.\n * **size** *(optional)* The number of bytes being sent through this stream.\n * **options** *(optional)* A hash of stream options\n\nThe tracker stream object is a pass through stream that updates an internal\ntracker object each time a block passes through. It's intended to track\ndownloads, file extraction and other related activities. You use it by piping\nyour data source into it and then using it as your data source.\n\nIf your data has a length attribute then that's used as the amount of work\ncompleted when the chunk is passed through. If it does not (eg, object\nstreams) then each chunk counts as completing 1 unit of work, so your size\nshould be the total number of objects being streamed.\n\n* tracker.addWork(**todo**)\n\n * **todo** Increase the expected overall size by **todo** bytes.\n\nIncreases the amount of work to be done, thus decreasing the completion\npercentage. Triggers a `change` event.\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+https://github.com/iarna/are-we-there-yet.git"
},
"scripts": {
"test": "standard && tap test/*.js"
},
"version": "1.1.4"
}
... ...
'use strict'
var EventEmitter = require('events').EventEmitter
var util = require('util')
var trackerId = 0
var TrackerBase = module.exports = function (name) {
EventEmitter.call(this)
this.id = ++trackerId
this.name = name
}
util.inherits(TrackerBase, EventEmitter)
... ...
'use strict'
var util = require('util')
var TrackerBase = require('./tracker-base.js')
var Tracker = require('./tracker.js')
var TrackerStream = require('./tracker-stream.js')
var TrackerGroup = module.exports = function (name) {
TrackerBase.call(this, name)
this.parentGroup = null
this.trackers = []
this.completion = {}
this.weight = {}
this.totalWeight = 0
this.finished = false
this.bubbleChange = bubbleChange(this)
}
util.inherits(TrackerGroup, TrackerBase)
function bubbleChange (trackerGroup) {
return function (name, completed, tracker) {
trackerGroup.completion[tracker.id] = completed
if (trackerGroup.finished) return
trackerGroup.emit('change', name || trackerGroup.name, trackerGroup.completed(), trackerGroup)
}
}
TrackerGroup.prototype.nameInTree = function () {
var names = []
var from = this
while (from) {
names.unshift(from.name)
from = from.parentGroup
}
return names.join('/')
}
TrackerGroup.prototype.addUnit = function (unit, weight) {
if (unit.addUnit) {
var toTest = this
while (toTest) {
if (unit === toTest) {
throw new Error(
'Attempted to add tracker group ' +
unit.name + ' to tree that already includes it ' +
this.nameInTree(this))
}
toTest = toTest.parentGroup
}
unit.parentGroup = this
}
this.weight[unit.id] = weight || 1
this.totalWeight += this.weight[unit.id]
this.trackers.push(unit)
this.completion[unit.id] = unit.completed()
unit.on('change', this.bubbleChange)
if (!this.finished) this.emit('change', unit.name, this.completion[unit.id], unit)
return unit
}
TrackerGroup.prototype.completed = function () {
if (this.trackers.length === 0) return 0
var valPerWeight = 1 / this.totalWeight
var completed = 0
for (var ii = 0; ii < this.trackers.length; ii++) {
var trackerId = this.trackers[ii].id
completed += valPerWeight * this.weight[trackerId] * this.completion[trackerId]
}
return completed
}
TrackerGroup.prototype.newGroup = function (name, weight) {
return this.addUnit(new TrackerGroup(name), weight)
}
TrackerGroup.prototype.newItem = function (name, todo, weight) {
return this.addUnit(new Tracker(name, todo), weight)
}
TrackerGroup.prototype.newStream = function (name, todo, weight) {
return this.addUnit(new TrackerStream(name, todo), weight)
}
TrackerGroup.prototype.finish = function () {
this.finished = true
if (!this.trackers.length) this.addUnit(new Tracker(), 1, true)
for (var ii = 0; ii < this.trackers.length; ii++) {
var tracker = this.trackers[ii]
tracker.finish()
tracker.removeListener('change', this.bubbleChange)
}
this.emit('change', this.name, 1, this)
}
var buffer = ' '
TrackerGroup.prototype.debug = function (depth) {
depth = depth || 0
var indent = depth ? buffer.substr(0, depth) : ''
var output = indent + (this.name || 'top') + ': ' + this.completed() + '\n'
this.trackers.forEach(function (tracker) {
if (tracker instanceof TrackerGroup) {
output += tracker.debug(depth + 1)
} else {
output += indent + ' ' + tracker.name + ': ' + tracker.completed() + '\n'
}
})
return output
}
... ...
'use strict'
var util = require('util')
var stream = require('readable-stream')
var delegate = require('delegates')
var Tracker = require('./tracker.js')
var TrackerStream = module.exports = function (name, size, options) {
stream.Transform.call(this, options)
this.tracker = new Tracker(name, size)
this.name = name
this.id = this.tracker.id
this.tracker.on('change', delegateChange(this))
}
util.inherits(TrackerStream, stream.Transform)
function delegateChange (trackerStream) {
return function (name, completion, tracker) {
trackerStream.emit('change', name, completion, trackerStream)
}
}
TrackerStream.prototype._transform = function (data, encoding, cb) {
this.tracker.completeWork(data.length ? data.length : 1)
this.push(data)
cb()
}
TrackerStream.prototype._flush = function (cb) {
this.tracker.finish()
cb()
}
delegate(TrackerStream.prototype, 'tracker')
.method('completed')
.method('addWork')
... ...
'use strict'
var util = require('util')
var TrackerBase = require('./tracker-base.js')
var Tracker = module.exports = function (name, todo) {
TrackerBase.call(this, name)
this.workDone = 0
this.workTodo = todo || 0
}
util.inherits(Tracker, TrackerBase)
Tracker.prototype.completed = function () {
return this.workTodo === 0 ? 0 : this.workDone / this.workTodo
}
Tracker.prototype.addWork = function (work) {
this.workTodo += work
this.emit('change', this.name, this.completed(), this)
}
Tracker.prototype.completeWork = function (work) {
this.workDone += work
if (this.workDone > this.workTodo) this.workDone = this.workTodo
this.emit('change', this.name, this.completed(), this)
}
Tracker.prototype.finish = function () {
this.workTodo = this.workDone = 1
this.emit('change', this.name, 1, this)
}
... ...
language: node_js
before_install:
- npm install -g npm@2
- npm install -g npm
matrix:
include:
- node_js: '0.8'
env: TASK=test-node
- node_js: '0.10'
env: TASK=test-node
- node_js: '0.11'
env: TASK=test-node
- node_js: '0.12'
env: TASK=test-node
- node_js: 1
env: TASK=test-node
- node_js: 2
env: TASK=test-node
- node_js: 3
env: TASK=test-node
- node_js: 4
env: TASK=test-node
- node_js: 5
env: TASK=test-node
- node_js: '0.10'
env: TASK=test-browser
script: "npm run $TASK"
env:
global:
- secure: qThuKBZQtkooAvzaYldECGNqvKGPRTnXx62IVyhSbFlsCY1VCmjhLldhyPDiZQ3JqL1XvSkK8OMDupiHqZnNE0nGijoO4M/kaEdjBB+jpjg3f8I6te2SNU935SbkfY9KHAaFXMZwdcq7Fk932AxWEu+FMSDM+080wNKpEATXDe4=
- secure: O/scKjHLRcPN5ILV5qsSkksQ7qcZQdHWEUUPItmj/4+vmCc28bHpicoUxXG5A96iHvkBbdmky/nGCg464ZaNLk68m6hfEMDAR3J6mhM2Pf5C4QI/LlFlR1fob9sQ8lztwSGOItwdK8Rfrgb30RRVV71f6FxnaJ6PKMuMNT5S1AQ=
... ...
ui: mocha-qunit
tunnel: ngrok
browsers:
- name: chrome
version: latest
- name: firefox
version: latest
- name: safari
version: latest
- name: ie
version: 9..latest
- name: microsoftedge
version: latest
... ...
Copyright Joyent, Inc. and other Node contributors. All rights reserved.
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.
... ...
# assert
[![Build Status](https://travis-ci.org/defunctzombie/commonjs-assert.svg?branch=master)](https://travis-ci.org/defunctzombie/commonjs-assert)
This module is used for writing unit tests for your applications, you can access it with require('assert').
The API is derived from the [commonjs 1.0 unit testing](http://wiki.commonjs.org/wiki/Unit_Testing/1.0) spec and the [node.js assert module](http://nodejs.org/api/assert.html)
## assert.fail(actual, expected, message, operator)
Throws an exception that displays the values for actual and expected separated by the provided operator.
## assert(value, message), assert.ok(value, [message])
Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message);
## assert.equal(actual, expected, [message])
Tests shallow, coercive equality with the equal comparison operator ( == ).
## assert.notEqual(actual, expected, [message])
Tests shallow, coercive non-equality with the not equal comparison operator ( != ).
## assert.deepEqual(actual, expected, [message])
Tests for deep equality.
## assert.notDeepEqual(actual, expected, [message])
Tests for any deep inequality.
## assert.strictEqual(actual, expected, [message])
Tests strict equality, as determined by the strict equality operator ( === )
## assert.notStrictEqual(actual, expected, [message])
Tests strict non-equality, as determined by the strict not equal operator ( !== )
## assert.throws(block, [error], [message])
Expects block to throw an error. error can be constructor, regexp or validation function.
Validate instanceof using constructor:
```javascript
assert.throws(function() { throw new Error("Wrong value"); }, Error);
```
Validate error message using RegExp:
```javascript
assert.throws(function() { throw new Error("Wrong value"); }, /value/);
```
Custom error validation:
```javascript
assert.throws(function() {
throw new Error("Wrong value");
}, function(err) {
if ( (err instanceof Error) && /value/.test(err) ) {
return true;
}
}, "unexpected error");
```
## assert.doesNotThrow(block, [message])
Expects block not to throw an error, see assert.throws for details.
## assert.ifError(value)
Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error in callbacks.
... ...
'use strict';
// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
// original notice:
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
function compare(a, b) {
if (a === b) {
return 0;
}
var x = a.length;
var y = b.length;
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break;
}
}
if (x < y) {
return -1;
}
if (y < x) {
return 1;
}
return 0;
}
function isBuffer(b) {
if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
return global.Buffer.isBuffer(b);
}
return !!(b != null && b._isBuffer);
}
// based on node assert, original notice:
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// 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 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.
var util = require('util/');
var hasOwn = Object.prototype.hasOwnProperty;
var pSlice = Array.prototype.slice;
var functionsHaveNames = (function () {
return function foo() {}.name === 'foo';
}());
function pToString (obj) {
return Object.prototype.toString.call(obj);
}
function isView(arrbuf) {
if (isBuffer(arrbuf)) {
return false;
}
if (typeof global.ArrayBuffer !== 'function') {
return false;
}
if (typeof ArrayBuffer.isView === 'function') {
return ArrayBuffer.isView(arrbuf);
}
if (!arrbuf) {
return false;
}
if (arrbuf instanceof DataView) {
return true;
}
if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
return true;
}
return false;
}
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
// expected: expected })
var regex = /\s*function\s+([^\(\s]*)\s*/;
// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
function getName(func) {
if (!util.isFunction(func)) {
return;
}
if (functionsHaveNames) {
return func.name;
}
var str = func.toString();
var match = str.match(regex);
return match && match[1];
}
assert.AssertionError = function AssertionError(options) {
this.name = 'AssertionError';
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
if (options.message) {
this.message = options.message;
this.generatedMessage = false;
} else {
this.message = getMessage(this);
this.generatedMessage = true;
}
var stackStartFunction = options.stackStartFunction || fail;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, stackStartFunction);
} else {
// non v8 browsers so we can have a stacktrace
var err = new Error();
if (err.stack) {
var out = err.stack;
// try to strip useless frames
var fn_name = getName(stackStartFunction);
var idx = out.indexOf('\n' + fn_name);
if (idx >= 0) {
// once we have located the function frame
// we need to strip out everything before it (and its line)
var next_line = out.indexOf('\n', idx + 1);
out = out.substring(next_line + 1);
}
this.stack = out;
}
}
};
// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);
function truncate(s, n) {
if (typeof s === 'string') {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
function inspect(something) {
if (functionsHaveNames || !util.isFunction(something)) {
return util.inspect(something);
}
var rawname = getName(something);
var name = rawname ? ': ' + rawname : '';
return '[Function' + name + ']';
}
function getMessage(self) {
return truncate(inspect(self.actual), 128) + ' ' +
self.operator + ' ' +
truncate(inspect(self.expected), 128);
}
// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.
// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;
// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.
function ok(value, message) {
if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected, false)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
if (!_deepEqual(actual, expected, true)) {
fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
}
};
function _deepEqual(actual, expected, strict, memos) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (isBuffer(actual) && isBuffer(expected)) {
return compare(actual, expected) === 0;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (util.isDate(actual) && util.isDate(expected)) {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (util.isRegExp(actual) && util.isRegExp(expected)) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if ((actual === null || typeof actual !== 'object') &&
(expected === null || typeof expected !== 'object')) {
return strict ? actual === expected : actual == expected;
// If both values are instances of typed arrays, wrap their underlying
// ArrayBuffers in a Buffer each to increase performance
// This optimization requires the arrays to have the same type as checked by
// Object.prototype.toString (aka pToString). Never perform binary
// comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
// bit patterns are not identical.
} else if (isView(actual) && isView(expected) &&
pToString(actual) === pToString(expected) &&
!(actual instanceof Float32Array ||
actual instanceof Float64Array)) {
return compare(new Uint8Array(actual.buffer),
new Uint8Array(expected.buffer)) === 0;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else if (isBuffer(actual) !== isBuffer(expected)) {
return false;
} else {
memos = memos || {actual: [], expected: []};
var actualIndex = memos.actual.indexOf(actual);
if (actualIndex !== -1) {
if (actualIndex === memos.expected.indexOf(expected)) {
return true;
}
}
memos.actual.push(actual);
memos.expected.push(expected);
return objEquiv(actual, expected, strict, memos);
}
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv(a, b, strict, actualVisitedObjects) {
if (a === null || a === undefined || b === null || b === undefined)
return false;
// if one is a primitive, the other must be same
if (util.isPrimitive(a) || util.isPrimitive(b))
return a === b;
if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
return false;
var aIsArgs = isArguments(a);
var bIsArgs = isArguments(b);
if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
return false;
if (aIsArgs) {
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b, strict);
}
var ka = objectKeys(a);
var kb = objectKeys(b);
var key, i;
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length !== kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] !== kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
return false;
}
return true;
}
// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected, false)) {
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
};
assert.notDeepStrictEqual = notDeepStrictEqual;
function notDeepStrictEqual(actual, expected, message) {
if (_deepEqual(actual, expected, true)) {
fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
}
}
// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, '===', assert.strictEqual);
}
};
// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, '!==', assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
return expected.test(actual);
}
try {
if (actual instanceof expected) {
return true;
}
} catch (e) {
// Ignore. The instanceof check doesn't work for arrow functions.
}
if (Error.isPrototypeOf(expected)) {
return false;
}
return expected.call({}, actual) === true;
}
function _tryBlock(block) {
var error;
try {
block();
} catch (e) {
error = e;
}
return error;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (typeof block !== 'function') {
throw new TypeError('"block" argument must be a function');
}
if (typeof expected === 'string') {
message = expected;
expected = null;
}
actual = _tryBlock(block);
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
(message ? ' ' + message : '.');
if (shouldThrow && !actual) {
fail(actual, expected, 'Missing expected exception' + message);
}
var userProvidedMessage = typeof message === 'string';
var isUnwantedException = !shouldThrow && util.isError(actual);
var isUnexpectedException = !shouldThrow && actual && !expected;
if ((isUnwantedException &&
userProvidedMessage &&
expectedException(actual, expected)) ||
isUnexpectedException) {
fail(actual, expected, 'Got unwanted exception' + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
throw actual;
}
}
// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws = function(block, /*optional*/error, /*optional*/message) {
_throws(true, block, error, message);
};
// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
_throws(false, block, error, message);
};
assert.ifError = function(err) { if (err) throw err; };
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
if (hasOwn.call(obj, key)) keys.push(key);
}
return keys;
};
... ...
{
"_args": [
[
{
"raw": "assert@>= 0.4.9",
"scope": null,
"escapedName": "assert",
"name": "assert",
"rawSpec": ">= 0.4.9",
"spec": ">=0.4.9",
"type": "range"
},
"/Users/fzy/project/koa2_Sequelize_project/node_modules/win32api"
]
],
"_from": "assert@>=0.4.9",
"_id": "assert@1.4.1",
"_inCache": true,
"_location": "/assert",
"_nodeVersion": "5.11.0",
"_npmOperationalInternal": {
"host": "packages-16-east.internal.npmjs.com",
"tmp": "tmp/assert-1.4.1.tgz_1464703323424_0.46298269950784743"
},
"_npmUser": {
"name": "cwmma",
"email": "calvin.metcalf@gmail.com"
},
"_npmVersion": "3.8.6",
"_phantomChildren": {},
"_requested": {
"raw": "assert@>= 0.4.9",
"scope": null,
"escapedName": "assert",
"name": "assert",
"rawSpec": ">= 0.4.9",
"spec": ">=0.4.9",
"type": "range"
},
"_requiredBy": [
"/win32api",
"/win32ole"
],
"_resolved": "https://registry.npmjs.org/assert/-/assert-1.4.1.tgz",
"_shasum": "99912d591836b5a6f5b345c0f07eefc08fc65d91",
"_shrinkwrap": null,
"_spec": "assert@>= 0.4.9",
"_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/win32api",
"bugs": {
"url": "https://github.com/defunctzombie/commonjs-assert/issues"
},
"dependencies": {
"util": "0.10.3"
},
"description": "commonjs assert - node.js api compatible",
"devDependencies": {
"mocha": "~1.21.4",
"zuul": "~3.10.0",
"zuul-ngrok": "^4.0.0"
},
"directories": {},
"dist": {
"shasum": "99912d591836b5a6f5b345c0f07eefc08fc65d91",
"tarball": "https://registry.npmjs.org/assert/-/assert-1.4.1.tgz"
},
"gitHead": "ea25d53a51201cf268681c5ec37f7d51b2d82884",
"homepage": "https://github.com/defunctzombie/commonjs-assert",
"keywords": [
"assert"
],
"license": "MIT",
"main": "./assert.js",
"maintainers": [
{
"name": "coolaj86",
"email": "coolaj86@gmail.com"
},
{
"name": "cwmma",
"email": "calvin.metcalf@gmail.com"
},
{
"name": "defunctzombie",
"email": "shtylman@gmail.com"
}
],
"name": "assert",
"optionalDependencies": {},
"readme": "# assert\n\n[![Build Status](https://travis-ci.org/defunctzombie/commonjs-assert.svg?branch=master)](https://travis-ci.org/defunctzombie/commonjs-assert)\n\nThis module is used for writing unit tests for your applications, you can access it with require('assert').\n\nThe API is derived from the [commonjs 1.0 unit testing](http://wiki.commonjs.org/wiki/Unit_Testing/1.0) spec and the [node.js assert module](http://nodejs.org/api/assert.html)\n\n## assert.fail(actual, expected, message, operator)\nThrows an exception that displays the values for actual and expected separated by the provided operator.\n\n## assert(value, message), assert.ok(value, [message])\nTests if value is truthy, it is equivalent to assert.equal(true, !!value, message);\n\n## assert.equal(actual, expected, [message])\nTests shallow, coercive equality with the equal comparison operator ( == ).\n\n## assert.notEqual(actual, expected, [message])\nTests shallow, coercive non-equality with the not equal comparison operator ( != ).\n\n## assert.deepEqual(actual, expected, [message])\nTests for deep equality.\n\n## assert.notDeepEqual(actual, expected, [message])\nTests for any deep inequality.\n\n## assert.strictEqual(actual, expected, [message])\nTests strict equality, as determined by the strict equality operator ( === )\n\n## assert.notStrictEqual(actual, expected, [message])\nTests strict non-equality, as determined by the strict not equal operator ( !== )\n\n## assert.throws(block, [error], [message])\nExpects block to throw an error. error can be constructor, regexp or validation function.\n\nValidate instanceof using constructor:\n\n```javascript\nassert.throws(function() { throw new Error(\"Wrong value\"); }, Error);\n```\n\nValidate error message using RegExp:\n\n```javascript\nassert.throws(function() { throw new Error(\"Wrong value\"); }, /value/);\n```\n\nCustom error validation:\n\n```javascript\nassert.throws(function() {\n throw new Error(\"Wrong value\");\n}, function(err) {\n if ( (err instanceof Error) && /value/.test(err) ) {\n return true;\n }\n}, \"unexpected error\");\n```\n\n## assert.doesNotThrow(block, [message])\nExpects block not to throw an error, see assert.throws for details.\n\n## assert.ifError(value)\nTests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error in callbacks.\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git://github.com/defunctzombie/commonjs-assert.git"
},
"scripts": {
"browser-local": "zuul --no-coverage --local 8000 -- test.js",
"test": "npm run test-node && npm run test-browser",
"test-browser": "zuul -- test.js",
"test-native": "TEST_NATIVE=true mocha --ui qunit test.js",
"test-node": "mocha --ui qunit test.js"
},
"version": "1.4.1"
}
... ...
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
var nodeAssert = require('assert');
var ourAssert = require('./');
var keys = Object.keys;
if (process.env.TEST_NATIVE === true) {
tests(nodeAssert, 'node assert');
} else {
tests(ourAssert, 'our assert');
}
function makeBlock(f) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
return f.apply(this, args);
};
}
function tests (assert, what) {
test('assert.ok', function () {
assert.throws(makeBlock(assert, false), assert.AssertionError, 'ok(false)');
assert.doesNotThrow(makeBlock(assert, true), assert.AssertionError, 'ok(true)');
assert.doesNotThrow(makeBlock(assert, 'test', 'ok(\'test\')'));
assert.throws(makeBlock(assert.ok, false),
assert.AssertionError, 'ok(false)');
assert.doesNotThrow(makeBlock(assert.ok, true),
assert.AssertionError, 'ok(true)');
assert.doesNotThrow(makeBlock(assert.ok, 'test'), 'ok(\'test\')');
});
test('assert.equal', function () {
assert.throws(makeBlock(assert.equal, true, false), assert.AssertionError, 'equal');
assert.doesNotThrow(makeBlock(assert.equal, null, null), 'equal');
assert.doesNotThrow(makeBlock(assert.equal, undefined, undefined), 'equal');
assert.doesNotThrow(makeBlock(assert.equal, null, undefined), 'equal');
assert.doesNotThrow(makeBlock(assert.equal, true, true), 'equal');
assert.doesNotThrow(makeBlock(assert.equal, 2, '2'), 'equal');
assert.doesNotThrow(makeBlock(assert.notEqual, true, false), 'notEqual');
assert.throws(makeBlock(assert.notEqual, true, true),
assert.AssertionError, 'notEqual');
});
test('assert.strictEqual', function () {
assert.throws(makeBlock(assert.strictEqual, 2, '2'),
assert.AssertionError, 'strictEqual');
assert.throws(makeBlock(assert.strictEqual, null, undefined),
assert.AssertionError, 'strictEqual');
assert.doesNotThrow(makeBlock(assert.notStrictEqual, 2, '2'), 'notStrictEqual');
});
test('assert.deepStrictEqual', function () {
assert.throws(makeBlock(assert.deepStrictEqual, [2], ['2']),
assert.AssertionError, 'deepStrictEqual');
assert.throws(makeBlock(assert.deepStrictEqual, [null], [undefined]),
assert.AssertionError, 'deepStrictEqual');
assert.doesNotThrow(makeBlock(assert.notDeepStrictEqual, [2], ['2']), 'notDeepStrictEqual');
});
test('assert.deepEqual - 7.2', function () {
assert.doesNotThrow(makeBlock(assert.deepEqual, new Date(2000, 3, 14),
new Date(2000, 3, 14)), 'deepEqual date');
assert.throws(makeBlock(assert.deepEqual, new Date(), new Date(2000, 3, 14)),
assert.AssertionError,
'deepEqual date');
});
test('assert.deepEqual - 7.3', function () {
assert.doesNotThrow(makeBlock(assert.deepEqual, /a/, /a/));
assert.doesNotThrow(makeBlock(assert.deepEqual, /a/g, /a/g));
assert.doesNotThrow(makeBlock(assert.deepEqual, /a/i, /a/i));
assert.doesNotThrow(makeBlock(assert.deepEqual, /a/m, /a/m));
assert.doesNotThrow(makeBlock(assert.deepEqual, /a/igm, /a/igm));
assert.throws(makeBlock(assert.deepEqual, /ab/, /a/));
assert.throws(makeBlock(assert.deepEqual, /a/g, /a/));
assert.throws(makeBlock(assert.deepEqual, /a/i, /a/));
assert.throws(makeBlock(assert.deepEqual, /a/m, /a/));
assert.throws(makeBlock(assert.deepEqual, /a/igm, /a/im));
var re1 = /a/;
re1.lastIndex = 3;
assert.throws(makeBlock(assert.deepEqual, re1, /a/));
});
test('assert.deepEqual - 7.4', function () {
assert.doesNotThrow(makeBlock(assert.deepEqual, 4, '4'), 'deepEqual == check');
assert.doesNotThrow(makeBlock(assert.deepEqual, true, 1), 'deepEqual == check');
assert.throws(makeBlock(assert.deepEqual, 4, '5'),
assert.AssertionError,
'deepEqual == check');
});
test('assert.deepEqual - 7.5', function () {
// having the same number of owned properties && the same set of keys
assert.doesNotThrow(makeBlock(assert.deepEqual, {a: 4}, {a: 4}));
assert.doesNotThrow(makeBlock(assert.deepEqual, {a: 4, b: '2'}, {a: 4, b: '2'}));
assert.doesNotThrow(makeBlock(assert.deepEqual, [4], ['4']));
assert.throws(makeBlock(assert.deepEqual, {a: 4}, {a: 4, b: true}),
assert.AssertionError);
assert.doesNotThrow(makeBlock(assert.deepEqual, ['a'], {0: 'a'}));
//(although not necessarily the same order),
assert.doesNotThrow(makeBlock(assert.deepEqual, {a: 4, b: '1'}, {b: '1', a: 4}));
var a1 = [1, 2, 3];
var a2 = [1, 2, 3];
a1.a = 'test';
a1.b = true;
a2.b = true;
a2.a = 'test';
assert.throws(makeBlock(assert.deepEqual, keys(a1), keys(a2)),
assert.AssertionError);
assert.doesNotThrow(makeBlock(assert.deepEqual, a1, a2));
});
test('assert.deepEqual - ES6 primitives', function () {
assert.throws(makeBlock(assert.deepEqual, null, {}), assert.AssertionError);
assert.throws(makeBlock(assert.deepEqual, undefined, {}), assert.AssertionError);
assert.throws(makeBlock(assert.deepEqual, 'a', ['a']), assert.AssertionError);
assert.throws(makeBlock(assert.deepEqual, 'a', {0: 'a'}), assert.AssertionError);
assert.throws(makeBlock(assert.deepEqual, 1, {}), assert.AssertionError);
assert.throws(makeBlock(assert.deepEqual, true, {}), assert.AssertionError);
if (typeof Symbol === 'symbol') {
assert.throws(makeBlock(assert.deepEqual, Symbol(), {}), assert.AssertionError);
}
});
test('assert.deepEqual - object wrappers', function () {
assert.doesNotThrow(makeBlock(assert.deepEqual, new String('a'), ['a']));
assert.doesNotThrow(makeBlock(assert.deepEqual, new String('a'), {0: 'a'}));
assert.doesNotThrow(makeBlock(assert.deepEqual, new Number(1), {}));
assert.doesNotThrow(makeBlock(assert.deepEqual, new Boolean(true), {}));
});
test('assert.deepEqual - Buffers', function () {
assert.doesNotThrow(makeBlock(assert.deepEqual, new Buffer([1, 2, 3]), new Buffer([1, 2, 3])));
if (typeof global.Uint8Array === 'function') {
assert.throws(makeBlock(assert.deepEqual, new Buffer([1, 2, 3]), new Uint8Array([1, 2, 3])));
}
if (typeof global.Uint16Array === 'function') {
assert.doesNotThrow(makeBlock(assert.deepEqual, new Uint16Array([1, 2, 3]), new Uint16Array([1, 2, 3])));
}
});
function thrower(errorConstructor) {
throw new errorConstructor('test');
}
test('assert - Testing the throwing', function () {
var aethrow = makeBlock(thrower, assert.AssertionError);
aethrow = makeBlock(thrower, assert.AssertionError);
// the basic calls work
assert.throws(makeBlock(thrower, assert.AssertionError),
assert.AssertionError, 'message');
assert.throws(makeBlock(thrower, assert.AssertionError), assert.AssertionError);
assert.throws(makeBlock(thrower, assert.AssertionError));
// if not passing an error, catch all.
assert.throws(makeBlock(thrower, TypeError));
// when passing a type, only catch errors of the appropriate type
var threw = false;
try {
assert.throws(makeBlock(thrower, TypeError), assert.AssertionError);
} catch (e) {
threw = true;
assert.ok(e instanceof TypeError, 'type');
}
assert.equal(true, threw,
'a.throws with an explicit error is eating extra errors',
assert.AssertionError);
threw = false;
// doesNotThrow should pass through all errors
try {
assert.doesNotThrow(makeBlock(thrower, TypeError), assert.AssertionError);
} catch (e) {
threw = true;
assert.ok(e instanceof TypeError);
}
assert.equal(true, threw,
'a.doesNotThrow with an explicit error is eating extra errors');
// key difference is that throwing our correct error makes an assertion error
try {
assert.doesNotThrow(makeBlock(thrower, TypeError), TypeError);
} catch (e) {
threw = true;
assert.ok(e instanceof assert.AssertionError);
}
assert.equal(true, threw,
'a.doesNotThrow is not catching type matching errors');
});
test('assert.ifError', function () {
assert.throws(function() {assert.ifError(new Error('test error'))});
assert.doesNotThrow(function() {assert.ifError(null)});
assert.doesNotThrow(function() {assert.ifError()});
});
test('assert - make sure that validating using constructor really works', function () {
var threw = false;
try {
assert.throws(
function() {
throw ({});
},
Array
);
} catch (e) {
threw = true;
}
assert.ok(threw, 'wrong constructor validation');
});
test('assert - use a RegExp to validate error message', function () {
assert.throws(makeBlock(thrower, TypeError), /test/);
});
test('assert - se a fn to validate error object', function () {
assert.throws(makeBlock(thrower, TypeError), function(err) {
if ((err instanceof TypeError) && /test/.test(err)) {
return true;
}
});
});
test('assert - Make sure deepEqual doesn\'t loop forever on circular refs', function () {
var b = {};
b.b = b;
var c = {};
c.b = c;
var gotError = false;
var equal = true;
try {
equal = assert.deepEqual(b, c);
} catch (e) {
gotError = true;
}
assert.ok(gotError || !equal, gotError ? 'got error': 'are equal');
});
test('assert - Ensure reflexivity of deepEqual with `arguments` objects', function() {
var args = (function() { return arguments; })();
assert.throws(makeBlock(assert.deepEqual, [], args), assert.AssertionError);
assert.throws(makeBlock(assert.deepEqual, args, []), assert.AssertionError);
});
test('assert - test assertion message', function () {
function testAssertionMessage(actual, expected) {
try {
assert.equal(actual, '');
} catch (e) {
assert.equal(e.toString(),
['AssertionError:', expected, '==', '\'\''].join(' '));
}
}
testAssertionMessage(undefined, 'undefined');
testAssertionMessage(null, 'null');
testAssertionMessage(true, 'true');
testAssertionMessage(false, 'false');
testAssertionMessage(0, '0');
testAssertionMessage(100, '100');
testAssertionMessage(NaN, 'NaN');
testAssertionMessage(Infinity, 'Infinity');
testAssertionMessage(-Infinity, '-Infinity');
testAssertionMessage('', '""');
testAssertionMessage('foo', '\'foo\'');
testAssertionMessage([], '[]');
testAssertionMessage([1, 2, 3], '[ 1, 2, 3 ]');
testAssertionMessage(new Buffer([1, 2, 3]), '<Buffer 01 02 03>');
if (typeof global.Uint8Array === 'function' && Object.getOwnPropertyNames( new Uint8Array([])).length === 0) {
// todo fix util.inspect
testAssertionMessage(new Uint8Array([1, 2, 3]), '{ \'0\': 1, \'1\': 2, \'2\': 3 }');
}
testAssertionMessage(/a/, '/a/');
testAssertionMessage(function f() {}, '[Function: f]');
testAssertionMessage({}, '{}');
testAssertionMessage({a: undefined, b: null}, '{ a: undefined, b: null }');
testAssertionMessage({a: NaN, b: Infinity, c: -Infinity},
'{ a: NaN, b: Infinity, c: -Infinity }');
});
test('assert - regressions from node.js testcase', function () {
var threw = false;
try {
assert.throws(function () {
assert.ifError(null);
});
} catch (e) {
threw = true;
assert.equal(e.message, 'Missing expected exception..');
}
assert.ok(threw);
try {
assert.equal(1, 2);
} catch (e) {
assert.equal(e.toString().split('\n')[0], 'AssertionError: 1 == 2');
}
try {
assert.equal(1, 2, 'oh no');
} catch (e) {
assert.equal(e.toString().split('\n')[0], 'AssertionError: oh no');
}
});
}
... ...
node-bindings
=============
### Helper module for loading your native module's .node file
This is a helper module for authors of Node.js native addon modules.
It is basically the "swiss army knife" of `require()`ing your native module's
`.node` file.
Throughout the course of Node's native addon history, addons have ended up being
compiled in a variety of different places, depending on which build tool and which
version of node was used. To make matters worse, now the _gyp_ build tool can
produce either a _Release_ or _Debug_ build, each being built into different
locations.
This module checks _all_ the possible locations that a native addon would be built
at, and returns the first one that loads successfully.
Installation
------------
Install with `npm`:
``` bash
$ npm install bindings
```
Or add it to the `"dependencies"` section of your _package.json_ file.
Example
-------
`require()`ing the proper bindings file for the current node version, platform
and architecture is as simple as:
``` js
var bindings = require('bindings')('binding.node')
// Use your bindings defined in your C files
bindings.your_c_function()
```
Nice Error Output
-----------------
When the `.node` file could not be loaded, `node-bindings` throws an Error with
a nice error message telling you exactly what was tried. You can also check the
`err.tries` Array property.
```
Error: Could not load the bindings file. Tried:
→ /Users/nrajlich/ref/build/binding.node
→ /Users/nrajlich/ref/build/Debug/binding.node
→ /Users/nrajlich/ref/build/Release/binding.node
→ /Users/nrajlich/ref/out/Debug/binding.node
→ /Users/nrajlich/ref/Debug/binding.node
→ /Users/nrajlich/ref/out/Release/binding.node
→ /Users/nrajlich/ref/Release/binding.node
→ /Users/nrajlich/ref/build/default/binding.node
→ /Users/nrajlich/ref/compiled/0.8.2/darwin/x64/binding.node
at bindings (/Users/nrajlich/ref/node_modules/bindings/bindings.js:84:13)
at Object.<anonymous> (/Users/nrajlich/ref/lib/ref.js:5:47)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
...
```
The searching for the `.node` file will originate from the first directory in which has a `package.json` file is found.
License
-------
(The MIT License)
Copyright (c) 2012 Nathan Rajlich &lt;nathan@tootallnate.net&gt;
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.
... ...
/**
* Module dependencies.
*/
var fs = require('fs')
, path = require('path')
, join = path.join
, dirname = path.dirname
, exists = ((fs.accessSync && function (path) { try { fs.accessSync(path); } catch (e) { return false; } return true; })
|| fs.existsSync || path.existsSync)
, defaults = {
arrow: process.env.NODE_BINDINGS_ARROW || ' → '
, compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled'
, platform: process.platform
, arch: process.arch
, version: process.versions.node
, bindings: 'bindings.node'
, try: [
// node-gyp's linked version in the "build" dir
[ 'module_root', 'build', 'bindings' ]
// node-waf and gyp_addon (a.k.a node-gyp)
, [ 'module_root', 'build', 'Debug', 'bindings' ]
, [ 'module_root', 'build', 'Release', 'bindings' ]
// Debug files, for development (legacy behavior, remove for node v0.9)
, [ 'module_root', 'out', 'Debug', 'bindings' ]
, [ 'module_root', 'Debug', 'bindings' ]
// Release files, but manually compiled (legacy behavior, remove for node v0.9)
, [ 'module_root', 'out', 'Release', 'bindings' ]
, [ 'module_root', 'Release', 'bindings' ]
// Legacy from node-waf, node <= 0.4.x
, [ 'module_root', 'build', 'default', 'bindings' ]
// Production "Release" buildtype binary (meh...)
, [ 'module_root', 'compiled', 'version', 'platform', 'arch', 'bindings' ]
]
}
/**
* The main `bindings()` function loads the compiled bindings for a given module.
* It uses V8's Error API to determine the parent filename that this function is
* being invoked from, which is then used to find the root directory.
*/
function bindings (opts) {
// Argument surgery
if (typeof opts == 'string') {
opts = { bindings: opts }
} else if (!opts) {
opts = {}
}
// maps `defaults` onto `opts` object
Object.keys(defaults).map(function(i) {
if (!(i in opts)) opts[i] = defaults[i];
});
// Get the module root
if (!opts.module_root) {
opts.module_root = exports.getRoot(exports.getFileName())
}
// Ensure the given bindings name ends with .node
if (path.extname(opts.bindings) != '.node') {
opts.bindings += '.node'
}
var tries = []
, i = 0
, l = opts.try.length
, n
, b
, err
for (; i<l; i++) {
n = join.apply(null, opts.try[i].map(function (p) {
return opts[p] || p
}))
tries.push(n)
try {
b = opts.path ? require.resolve(n) : require(n)
if (!opts.path) {
b.path = n
}
return b
} catch (e) {
if (!/not find/i.test(e.message)) {
throw e
}
}
}
err = new Error('Could not locate the bindings file. Tried:\n'
+ tries.map(function (a) { return opts.arrow + a }).join('\n'))
err.tries = tries
throw err
}
module.exports = exports = bindings
/**
* Gets the filename of the JavaScript file that invokes this function.
* Used to help find the root directory of a module.
* Optionally accepts an filename argument to skip when searching for the invoking filename
*/
exports.getFileName = function getFileName (calling_file) {
var origPST = Error.prepareStackTrace
, origSTL = Error.stackTraceLimit
, dummy = {}
, fileName
Error.stackTraceLimit = 10
Error.prepareStackTrace = function (e, st) {
for (var i=0, l=st.length; i<l; i++) {
fileName = st[i].getFileName()
if (fileName !== __filename) {
if (calling_file) {
if (fileName !== calling_file) {
return
}
} else {
return
}
}
}
}
// run the 'prepareStackTrace' function above
Error.captureStackTrace(dummy)
dummy.stack
// cleanup
Error.prepareStackTrace = origPST
Error.stackTraceLimit = origSTL
return fileName
}
/**
* Gets the root directory of a module, given an arbitrary filename
* somewhere in the module tree. The "root directory" is the directory
* containing the `package.json` file.
*
* In: /home/nate/node-native-module/lib/index.js
* Out: /home/nate/node-native-module
*/
exports.getRoot = function getRoot (file) {
var dir = dirname(file)
, prev
while (true) {
if (dir === '.') {
// Avoids an infinite loop in rare cases, like the REPL
dir = process.cwd()
}
if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) {
// Found the 'package.json' file or 'node_modules' dir; we're done
return dir
}
if (prev === dir) {
// Got to the top
throw new Error('Could not find module root given file: "' + file
+ '". Do you have a `package.json` file? ')
}
// Try the parent dir next
prev = dir
dir = join(dir, '..')
}
}
... ...
{
"_args": [
[
{
"raw": "bindings@1",
"scope": null,
"escapedName": "bindings",
"name": "bindings",
"rawSpec": "1",
"spec": ">=1.0.0 <2.0.0",
"type": "range"
},
"/Users/fzy/project/koa2_Sequelize_project/node_modules/node-proxy"
]
],
"_from": "bindings@>=1.0.0 <2.0.0",
"_id": "bindings@1.3.0",
"_inCache": true,
"_location": "/bindings",
"_nodeVersion": "8.1.3",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/bindings-1.3.0.tgz_1500923768710_0.3334669852629304"
},
"_npmUser": {
"name": "tootallnate",
"email": "nathan@tootallnate.net"
},
"_npmVersion": "5.0.3",
"_phantomChildren": {},
"_requested": {
"raw": "bindings@1",
"scope": null,
"escapedName": "bindings",
"name": "bindings",
"rawSpec": "1",
"spec": ">=1.0.0 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/node-proxy",
"/ref"
],
"_resolved": "https://registry.npmjs.org/bindings/-/bindings-1.3.0.tgz",
"_shasum": "b346f6ecf6a95f5a815c5839fc7cdb22502f1ed7",
"_shrinkwrap": null,
"_spec": "bindings@1",
"_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/node-proxy",
"author": {
"name": "Nathan Rajlich",
"email": "nathan@tootallnate.net",
"url": "http://tootallnate.net"
},
"bugs": {
"url": "https://github.com/TooTallNate/node-bindings/issues"
},
"dependencies": {},
"description": "Helper module for loading your native module's .node file",
"devDependencies": {},
"directories": {},
"dist": {
"integrity": "sha512-DpLh5EzMR2kzvX1KIlVC0VkC3iZtHKTgdtZ0a3pglBZdaQFjt5S9g9xd1lE+YvXyfd6mtCeRnrUfOLYiTMlNSw==",
"shasum": "b346f6ecf6a95f5a815c5839fc7cdb22502f1ed7",
"tarball": "https://registry.npmjs.org/bindings/-/bindings-1.3.0.tgz"
},
"gitHead": "7fd065ee85386ad3d074d2506e03abe8f9b1588b",
"homepage": "https://github.com/TooTallNate/node-bindings",
"keywords": [
"native",
"addon",
"bindings",
"gyp",
"waf",
"c",
"c++"
],
"license": "MIT",
"main": "./bindings.js",
"maintainers": [
{
"name": "tootallnate",
"email": "nathan@tootallnate.net"
}
],
"name": "bindings",
"optionalDependencies": {},
"readme": "node-bindings\n=============\n### Helper module for loading your native module's .node file\n\nThis is a helper module for authors of Node.js native addon modules.\nIt is basically the \"swiss army knife\" of `require()`ing your native module's\n`.node` file.\n\nThroughout the course of Node's native addon history, addons have ended up being\ncompiled in a variety of different places, depending on which build tool and which\nversion of node was used. To make matters worse, now the _gyp_ build tool can\nproduce either a _Release_ or _Debug_ build, each being built into different\nlocations.\n\nThis module checks _all_ the possible locations that a native addon would be built\nat, and returns the first one that loads successfully.\n\n\nInstallation\n------------\n\nInstall with `npm`:\n\n``` bash\n$ npm install bindings\n```\n\nOr add it to the `\"dependencies\"` section of your _package.json_ file.\n\n\nExample\n-------\n\n`require()`ing the proper bindings file for the current node version, platform\nand architecture is as simple as:\n\n``` js\nvar bindings = require('bindings')('binding.node')\n\n// Use your bindings defined in your C files\nbindings.your_c_function()\n```\n\n\nNice Error Output\n-----------------\n\nWhen the `.node` file could not be loaded, `node-bindings` throws an Error with\na nice error message telling you exactly what was tried. You can also check the\n`err.tries` Array property.\n\n```\nError: Could not load the bindings file. Tried:\n → /Users/nrajlich/ref/build/binding.node\n → /Users/nrajlich/ref/build/Debug/binding.node\n → /Users/nrajlich/ref/build/Release/binding.node\n → /Users/nrajlich/ref/out/Debug/binding.node\n → /Users/nrajlich/ref/Debug/binding.node\n → /Users/nrajlich/ref/out/Release/binding.node\n → /Users/nrajlich/ref/Release/binding.node\n → /Users/nrajlich/ref/build/default/binding.node\n → /Users/nrajlich/ref/compiled/0.8.2/darwin/x64/binding.node\n at bindings (/Users/nrajlich/ref/node_modules/bindings/bindings.js:84:13)\n at Object.<anonymous> (/Users/nrajlich/ref/lib/ref.js:5:47)\n at Module._compile (module.js:449:26)\n at Object.Module._extensions..js (module.js:467:10)\n at Module.load (module.js:356:32)\n at Function.Module._load (module.js:312:12)\n ...\n```\n\nThe searching for the `.node` file will originate from the first directory in which has a `package.json` file is found. \n\nLicense\n-------\n\n(The MIT License)\n\nCopyright (c) 2012 Nathan Rajlich &lt;nathan@tootallnate.net&gt;\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git://github.com/TooTallNate/node-bindings.git"
},
"version": "1.3.0"
}
... ...
Copyright (c) Isaac Z. Schlueter
All rights reserved.
The BSD License
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
... ...
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
... ...
# block-stream
A stream of blocks.
Write data into it, and it'll output data in buffer blocks the size you
specify, padding with zeroes if necessary.
```javascript
var block = new BlockStream(512)
fs.createReadStream("some-file").pipe(block)
block.pipe(fs.createWriteStream("block-file"))
```
When `.end()` or `.flush()` is called, it'll pad the block with zeroes.
... ...
// write data to it, and it'll emit data in 512 byte blocks.
// if you .end() or .flush(), it'll emit whatever it's got,
// padded with nulls to 512 bytes.
module.exports = BlockStream
var Stream = require("stream").Stream
, inherits = require("inherits")
, assert = require("assert").ok
, debug = process.env.DEBUG ? console.error : function () {}
function BlockStream (size, opt) {
this.writable = this.readable = true
this._opt = opt || {}
this._chunkSize = size || 512
this._offset = 0
this._buffer = []
this._bufferLength = 0
if (this._opt.nopad) this._zeroes = false
else {
this._zeroes = new Buffer(this._chunkSize)
for (var i = 0; i < this._chunkSize; i ++) {
this._zeroes[i] = 0
}
}
}
inherits(BlockStream, Stream)
BlockStream.prototype.write = function (c) {
// debug(" BS write", c)
if (this._ended) throw new Error("BlockStream: write after end")
if (c && !Buffer.isBuffer(c)) c = new Buffer(c + "")
if (c.length) {
this._buffer.push(c)
this._bufferLength += c.length
}
// debug("pushed onto buffer", this._bufferLength)
if (this._bufferLength >= this._chunkSize) {
if (this._paused) {
// debug(" BS paused, return false, need drain")
this._needDrain = true
return false
}
this._emitChunk()
}
return true
}
BlockStream.prototype.pause = function () {
// debug(" BS pausing")
this._paused = true
}
BlockStream.prototype.resume = function () {
// debug(" BS resume")
this._paused = false
return this._emitChunk()
}
BlockStream.prototype.end = function (chunk) {
// debug("end", chunk)
if (typeof chunk === "function") cb = chunk, chunk = null
if (chunk) this.write(chunk)
this._ended = true
this.flush()
}
BlockStream.prototype.flush = function () {
this._emitChunk(true)
}
BlockStream.prototype._emitChunk = function (flush) {
// debug("emitChunk flush=%j emitting=%j paused=%j", flush, this._emitting, this._paused)
// emit a <chunkSize> chunk
if (flush && this._zeroes) {
// debug(" BS push zeroes", this._bufferLength)
// push a chunk of zeroes
var padBytes = (this._bufferLength % this._chunkSize)
if (padBytes !== 0) padBytes = this._chunkSize - padBytes
if (padBytes > 0) {
// debug("padBytes", padBytes, this._zeroes.slice(0, padBytes))
this._buffer.push(this._zeroes.slice(0, padBytes))
this._bufferLength += padBytes
// debug(this._buffer[this._buffer.length - 1].length, this._bufferLength)
}
}
if (this._emitting || this._paused) return
this._emitting = true
// debug(" BS entering loops")
var bufferIndex = 0
while (this._bufferLength >= this._chunkSize &&
(flush || !this._paused)) {
// debug(" BS data emission loop", this._bufferLength)
var out
, outOffset = 0
, outHas = this._chunkSize
while (outHas > 0 && (flush || !this._paused) ) {
// debug(" BS data inner emit loop", this._bufferLength)
var cur = this._buffer[bufferIndex]
, curHas = cur.length - this._offset
// debug("cur=", cur)
// debug("curHas=%j", curHas)
// If it's not big enough to fill the whole thing, then we'll need
// to copy multiple buffers into one. However, if it is big enough,
// then just slice out the part we want, to save unnecessary copying.
// Also, need to copy if we've already done some copying, since buffers
// can't be joined like cons strings.
if (out || curHas < outHas) {
out = out || new Buffer(this._chunkSize)
cur.copy(out, outOffset,
this._offset, this._offset + Math.min(curHas, outHas))
} else if (cur.length === outHas && this._offset === 0) {
// shortcut -- cur is exactly long enough, and no offset.
out = cur
} else {
// slice out the piece of cur that we need.
out = cur.slice(this._offset, this._offset + outHas)
}
if (curHas > outHas) {
// means that the current buffer couldn't be completely output
// update this._offset to reflect how much WAS written
this._offset += outHas
outHas = 0
} else {
// output the entire current chunk.
// toss it away
outHas -= curHas
outOffset += curHas
bufferIndex ++
this._offset = 0
}
}
this._bufferLength -= this._chunkSize
assert(out.length === this._chunkSize)
// debug("emitting data", out)
// debug(" BS emitting, paused=%j", this._paused, this._bufferLength)
this.emit("data", out)
out = null
}
// debug(" BS out of loops", this._bufferLength)
// whatever is left, it's not enough to fill up a block, or we're paused
this._buffer = this._buffer.slice(bufferIndex)
if (this._paused) {
// debug(" BS paused, leaving", this._bufferLength)
this._needsDrain = true
this._emitting = false
return
}
// if flushing, and not using null-padding, then need to emit the last
// chunk(s) sitting in the queue. We know that it's not enough to
// fill up a whole block, because otherwise it would have been emitted
// above, but there may be some offset.
var l = this._buffer.length
if (flush && !this._zeroes && l) {
if (l === 1) {
if (this._offset) {
this.emit("data", this._buffer[0].slice(this._offset))
} else {
this.emit("data", this._buffer[0])
}
} else {
var outHas = this._bufferLength
, out = new Buffer(outHas)
, outOffset = 0
for (var i = 0; i < l; i ++) {
var cur = this._buffer[i]
, curHas = cur.length - this._offset
cur.copy(out, outOffset, this._offset)
this._offset = 0
outOffset += curHas
this._bufferLength -= curHas
}
this.emit("data", out)
}
// truncate
this._buffer.length = 0
this._bufferLength = 0
this._offset = 0
}
// now either drained or ended
// debug("either draining, or ended", this._bufferLength, this._ended)
// means that we've flushed out all that we can so far.
if (this._needDrain) {
// debug("emitting drain", this._bufferLength)
this._needDrain = false
this.emit("drain")
}
if ((this._bufferLength === 0) && this._ended && !this._endEmitted) {
// debug("emitting end", this._bufferLength)
this._endEmitted = true
this.emit("end")
}
this._emitting = false
// debug(" BS no longer emitting", flush, this._paused, this._emitting, this._bufferLength, this._chunkSize)
}
... ...
{
"_args": [
[
{
"raw": "block-stream@*",
"scope": null,
"escapedName": "block-stream",
"name": "block-stream",
"rawSpec": "*",
"spec": "*",
"type": "range"
},
"/Users/fzy/project/koa2_Sequelize_project/node_modules/tar"
]
],
"_from": "block-stream@*",
"_id": "block-stream@0.0.9",
"_inCache": true,
"_location": "/block-stream",
"_nodeVersion": "5.6.0",
"_npmOperationalInternal": {
"host": "packages-16-east.internal.npmjs.com",
"tmp": "tmp/block-stream-0.0.9.tgz_1462149852620_0.6890447810292244"
},
"_npmUser": {
"name": "isaacs",
"email": "i@izs.me"
},
"_npmVersion": "3.8.5",
"_phantomChildren": {},
"_requested": {
"raw": "block-stream@*",
"scope": null,
"escapedName": "block-stream",
"name": "block-stream",
"rawSpec": "*",
"spec": "*",
"type": "range"
},
"_requiredBy": [
"/tar"
],
"_resolved": "https://registry.npmjs.org/block-stream/-/block-stream-0.0.9.tgz",
"_shasum": "13ebfe778a03205cfe03751481ebb4b3300c126a",
"_shrinkwrap": null,
"_spec": "block-stream@*",
"_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/tar",
"author": {
"name": "Isaac Z. Schlueter",
"email": "i@izs.me",
"url": "http://blog.izs.me/"
},
"bugs": {
"url": "https://github.com/isaacs/block-stream/issues"
},
"dependencies": {
"inherits": "~2.0.0"
},
"description": "a stream of blocks",
"devDependencies": {
"tap": "^5.7.1"
},
"directories": {},
"dist": {
"shasum": "13ebfe778a03205cfe03751481ebb4b3300c126a",
"tarball": "https://registry.npmjs.org/block-stream/-/block-stream-0.0.9.tgz"
},
"engines": {
"node": "0.4 || >=0.5.8"
},
"files": [
"block-stream.js"
],
"gitHead": "321cf242ef6d130bb2e59c0565a61ded5dd2673f",
"homepage": "https://github.com/isaacs/block-stream#readme",
"license": "ISC",
"main": "block-stream.js",
"maintainers": [
{
"name": "isaacs",
"email": "i@izs.me"
}
],
"name": "block-stream",
"optionalDependencies": {},
"readme": "# block-stream\n\nA stream of blocks.\n\nWrite data into it, and it'll output data in buffer blocks the size you\nspecify, padding with zeroes if necessary.\n\n```javascript\nvar block = new BlockStream(512)\nfs.createReadStream(\"some-file\").pipe(block)\nblock.pipe(fs.createWriteStream(\"block-file\"))\n```\n\nWhen `.end()` or `.flush()` is called, it'll pad the block with zeroes.\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git://github.com/isaacs/block-stream.git"
},
"scripts": {
"test": "tap test/*.js --cov"
},
"version": "0.0.9"
}
... ...
/* eslint-disable babel/new-cap, xo/throw-new-error */
'use strict';
module.exports = function (str, pos) {
if (str === null || str === undefined) {
throw TypeError();
}
str = String(str);
var size = str.length;
var i = pos ? Number(pos) : 0;
if (Number.isNaN(i)) {
i = 0;
}
if (i < 0 || i >= size) {
return undefined;
}
var first = str.charCodeAt(i);
if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) {
var second = str.charCodeAt(i + 1);
if (second >= 0xDC00 && second <= 0xDFFF) {
return ((first - 0xD800) * 0x400) + second - 0xDC00 + 0x10000;
}
}
return first;
};
... ...
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
... ...
{
"_args": [
[
{
"raw": "code-point-at@^1.0.0",
"scope": null,
"escapedName": "code-point-at",
"name": "code-point-at",
"rawSpec": "^1.0.0",
"spec": ">=1.0.0 <2.0.0",
"type": "range"
},
"/Users/fzy/project/koa2_Sequelize_project/node_modules/string-width"
]
],
"_from": "code-point-at@>=1.0.0 <2.0.0",
"_id": "code-point-at@1.1.0",
"_inCache": true,
"_location": "/code-point-at",
"_nodeVersion": "4.6.1",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/code-point-at-1.1.0.tgz_1478169780337_0.8445875702891499"
},
"_npmUser": {
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
"_npmVersion": "2.15.9",
"_phantomChildren": {},
"_requested": {
"raw": "code-point-at@^1.0.0",
"scope": null,
"escapedName": "code-point-at",
"name": "code-point-at",
"rawSpec": "^1.0.0",
"spec": ">=1.0.0 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/string-width"
],
"_resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz",
"_shasum": "0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77",
"_shrinkwrap": null,
"_spec": "code-point-at@^1.0.0",
"_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/string-width",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/code-point-at/issues"
},
"dependencies": {},
"description": "ES2015 `String#codePointAt()` ponyfill",
"devDependencies": {
"ava": "*",
"xo": "^0.16.0"
},
"directories": {},
"dist": {
"shasum": "0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77",
"tarball": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"gitHead": "f8f21c8df2d40248fef1b36ca9076e59c0c34791",
"homepage": "https://github.com/sindresorhus/code-point-at#readme",
"keywords": [
"es2015",
"ponyfill",
"polyfill",
"shim",
"string",
"str",
"code",
"point",
"at",
"codepoint",
"unicode"
],
"license": "MIT",
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"name": "code-point-at",
"optionalDependencies": {},
"readme": "# code-point-at [![Build Status](https://travis-ci.org/sindresorhus/code-point-at.svg?branch=master)](https://travis-ci.org/sindresorhus/code-point-at)\n\n> ES2015 [`String#codePointAt()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) [ponyfill](https://ponyfill.com)\n\n\n## Install\n\n```\n$ npm install --save code-point-at\n```\n\n\n## Usage\n\n```js\nvar codePointAt = require('code-point-at');\n\ncodePointAt('🐴');\n//=> 128052\n\ncodePointAt('abc', 2);\n//=> 99\n```\n\n## API\n\n### codePointAt(input, [position])\n\n\n## License\n\nMIT © [Sindre Sorhus](https://sindresorhus.com)\n",
"readmeFilename": "readme.md",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/code-point-at.git"
},
"scripts": {
"test": "xo && ava"
},
"version": "1.1.0"
}
... ...
# code-point-at [![Build Status](https://travis-ci.org/sindresorhus/code-point-at.svg?branch=master)](https://travis-ci.org/sindresorhus/code-point-at)
> ES2015 [`String#codePointAt()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt) [ponyfill](https://ponyfill.com)
## Install
```
$ npm install --save code-point-at
```
## Usage
```js
var codePointAt = require('code-point-at');
codePointAt('🐴');
//=> 128052
codePointAt('abc', 2);
//=> 99
```
## API
### codePointAt(input, [position])
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
... ...
Copyright (c) 2014, Rebecca Turner <me@re-becca.org>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
... ...
# Console Control Strings
A library of cross-platform tested terminal/console command strings for
doing things like color and cursor positioning. This is a subset of both
ansi and vt100. All control codes included work on both Windows & Unix-like
OSes, except where noted.
## Usage
```js
var consoleControl = require('console-control-strings')
console.log(consoleControl.color('blue','bgRed', 'bold') + 'hi there' + consoleControl.color('reset'))
process.stdout.write(consoleControl.goto(75, 10))
```
## Why Another?
There are tons of libraries similar to this one. I wanted one that was:
1. Very clear about compatibility goals.
2. Could emit, for instance, a start color code without an end one.
3. Returned strings w/o writing to streams.
4. Was not weighed down with other unrelated baggage.
## Functions
### var code = consoleControl.up(_num = 1_)
Returns the escape sequence to move _num_ lines up.
### var code = consoleControl.down(_num = 1_)
Returns the escape sequence to move _num_ lines down.
### var code = consoleControl.forward(_num = 1_)
Returns the escape sequence to move _num_ lines righ.
### var code = consoleControl.back(_num = 1_)
Returns the escape sequence to move _num_ lines left.
### var code = consoleControl.nextLine(_num = 1_)
Returns the escape sequence to move _num_ lines down and to the beginning of
the line.
### var code = consoleControl.previousLine(_num = 1_)
Returns the escape sequence to move _num_ lines up and to the beginning of
the line.
### var code = consoleControl.eraseData()
Returns the escape sequence to erase everything from the current cursor
position to the bottom right of the screen. This is line based, so it
erases the remainder of the current line and all following lines.
### var code = consoleControl.eraseLine()
Returns the escape sequence to erase to the end of the current line.
### var code = consoleControl.goto(_x_, _y_)
Returns the escape sequence to move the cursor to the designated position.
Note that the origin is _1, 1_ not _0, 0_.
### var code = consoleControl.gotoSOL()
Returns the escape sequence to move the cursor to the beginning of the
current line. (That is, it returns a carriage return, `\r`.)
### var code = consoleControl.beep()
Returns the escape sequence to cause the termianl to beep. (That is, it
returns unicode character `\x0007`, a Control-G.)
### var code = consoleControl.hideCursor()
Returns the escape sequence to hide the cursor.
### var code = consoleControl.showCursor()
Returns the escape sequence to show the cursor.
### var code = consoleControl.color(_colors = []_)
### var code = consoleControl.color(_color1_, _color2_, _…_, _colorn_)
Returns the escape sequence to set the current terminal display attributes
(mostly colors). Arguments can either be a list of attributes or an array
of attributes. The difference between passing in an array or list of colors
and calling `.color` separately for each one, is that in the former case a
single escape sequence will be produced where as in the latter each change
will have its own distinct escape sequence. Each attribute can be one of:
* Reset:
* **reset** – Reset all attributes to the terminal default.
* Styles:
* **bold** – Display text as bold. In some terminals this means using a
bold font, in others this means changing the color. In some it means
both.
* **italic** – Display text as italic. This is not available in most Windows terminals.
* **underline** – Underline text. This is not available in most Windows Terminals.
* **inverse** – Invert the foreground and background colors.
* **stopBold** – Do not display text as bold.
* **stopItalic** – Do not display text as italic.
* **stopUnderline** – Do not underline text.
* **stopInverse** – Do not invert foreground and background.
* Colors:
* **white**
* **black**
* **blue**
* **cyan**
* **green**
* **magenta**
* **red**
* **yellow**
* **grey** / **brightBlack**
* **brightRed**
* **brightGreen**
* **brightYellow**
* **brightBlue**
* **brightMagenta**
* **brightCyan**
* **brightWhite**
* Background Colors:
* **bgWhite**
* **bgBlack**
* **bgBlue**
* **bgCyan**
* **bgGreen**
* **bgMagenta**
* **bgRed**
* **bgYellow**
* **bgGrey** / **bgBrightBlack**
* **bgBrightRed**
* **bgBrightGreen**
* **bgBrightYellow**
* **bgBrightBlue**
* **bgBrightMagenta**
* **bgBrightCyan**
* **bgBrightWhite**
... ...
'use strict'
// These tables borrowed from `ansi`
var prefix = '\x1b['
exports.up = function up (num) {
return prefix + (num || '') + 'A'
}
exports.down = function down (num) {
return prefix + (num || '') + 'B'
}
exports.forward = function forward (num) {
return prefix + (num || '') + 'C'
}
exports.back = function back (num) {
return prefix + (num || '') + 'D'
}
exports.nextLine = function nextLine (num) {
return prefix + (num || '') + 'E'
}
exports.previousLine = function previousLine (num) {
return prefix + (num || '') + 'F'
}
exports.horizontalAbsolute = function horizontalAbsolute (num) {
if (num == null) throw new Error('horizontalAboslute requires a column to position to')
return prefix + num + 'G'
}
exports.eraseData = function eraseData () {
return prefix + 'J'
}
exports.eraseLine = function eraseLine () {
return prefix + 'K'
}
exports.goto = function (x, y) {
return prefix + y + ';' + x + 'H'
}
exports.gotoSOL = function () {
return '\r'
}
exports.beep = function () {
return '\x07'
}
exports.hideCursor = function hideCursor () {
return prefix + '?25l'
}
exports.showCursor = function showCursor () {
return prefix + '?25h'
}
var colors = {
reset: 0,
// styles
bold: 1,
italic: 3,
underline: 4,
inverse: 7,
// resets
stopBold: 22,
stopItalic: 23,
stopUnderline: 24,
stopInverse: 27,
// colors
white: 37,
black: 30,
blue: 34,
cyan: 36,
green: 32,
magenta: 35,
red: 31,
yellow: 33,
bgWhite: 47,
bgBlack: 40,
bgBlue: 44,
bgCyan: 46,
bgGreen: 42,
bgMagenta: 45,
bgRed: 41,
bgYellow: 43,
grey: 90,
brightBlack: 90,
brightRed: 91,
brightGreen: 92,
brightYellow: 93,
brightBlue: 94,
brightMagenta: 95,
brightCyan: 96,
brightWhite: 97,
bgGrey: 100,
bgBrightBlack: 100,
bgBrightRed: 101,
bgBrightGreen: 102,
bgBrightYellow: 103,
bgBrightBlue: 104,
bgBrightMagenta: 105,
bgBrightCyan: 106,
bgBrightWhite: 107
}
exports.color = function color (colorWith) {
if (arguments.length !== 1 || !Array.isArray(colorWith)) {
colorWith = Array.prototype.slice.call(arguments)
}
return prefix + colorWith.map(colorNameToCode).join(';') + 'm'
}
function colorNameToCode (color) {
if (colors[color] != null) return colors[color]
throw new Error('Unknown color or style name: ' + color)
}
... ...
{
"_args": [
[
{
"raw": "console-control-strings@~1.1.0",
"scope": null,
"escapedName": "console-control-strings",
"name": "console-control-strings",
"rawSpec": "~1.1.0",
"spec": ">=1.1.0 <1.2.0",
"type": "range"
},
"/Users/fzy/project/koa2_Sequelize_project/node_modules/npmlog"
]
],
"_from": "console-control-strings@>=1.1.0 <1.2.0",
"_id": "console-control-strings@1.1.0",
"_inCache": true,
"_location": "/console-control-strings",
"_nodeVersion": "4.4.0",
"_npmOperationalInternal": {
"host": "packages-16-east.internal.npmjs.com",
"tmp": "tmp/console-control-strings-1.1.0.tgz_1466033396831_0.9470485949423164"
},
"_npmUser": {
"name": "iarna",
"email": "me@re-becca.org"
},
"_npmVersion": "3.9.2",
"_phantomChildren": {},
"_requested": {
"raw": "console-control-strings@~1.1.0",
"scope": null,
"escapedName": "console-control-strings",
"name": "console-control-strings",
"rawSpec": "~1.1.0",
"spec": ">=1.1.0 <1.2.0",
"type": "range"
},
"_requiredBy": [
"/gauge",
"/npmlog"
],
"_resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",
"_shasum": "3d7cf4464db6446ea644bf4b39507f9851008e8e",
"_shrinkwrap": null,
"_spec": "console-control-strings@~1.1.0",
"_where": "/Users/fzy/project/koa2_Sequelize_project/node_modules/npmlog",
"author": {
"name": "Rebecca Turner",
"email": "me@re-becca.org",
"url": "http://re-becca.org/"
},
"bugs": {
"url": "https://github.com/iarna/console-control-strings/issues"
},
"dependencies": {},
"description": "A library of cross-platform tested terminal/console command strings for doing things like color and cursor positioning. This is a subset of both ansi and vt100. All control codes included work on both Windows & Unix-like OSes, except where noted.",
"devDependencies": {
"standard": "^7.1.2",
"tap": "^5.7.2"
},
"directories": {
"test": "test"
},
"dist": {
"shasum": "3d7cf4464db6446ea644bf4b39507f9851008e8e",
"tarball": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz"
},
"files": [
"LICENSE",
"index.js"
],
"gitHead": "722439b4998d2964ac3d3f9ec175c008aa9b7b4b",
"homepage": "https://github.com/iarna/console-control-strings#readme",
"keywords": [],
"license": "ISC",
"main": "index.js",
"maintainers": [
{
"name": "iarna",
"email": "me@re-becca.org"
}
],
"name": "console-control-strings",
"optionalDependencies": {},
"readme": "# Console Control Strings\n\nA library of cross-platform tested terminal/console command strings for\ndoing things like color and cursor positioning. This is a subset of both\nansi and vt100. All control codes included work on both Windows & Unix-like\nOSes, except where noted.\n\n## Usage\n\n```js\nvar consoleControl = require('console-control-strings')\n\nconsole.log(consoleControl.color('blue','bgRed', 'bold') + 'hi there' + consoleControl.color('reset'))\nprocess.stdout.write(consoleControl.goto(75, 10))\n```\n\n## Why Another?\n\nThere are tons of libraries similar to this one. I wanted one that was:\n\n1. Very clear about compatibility goals.\n2. Could emit, for instance, a start color code without an end one.\n3. Returned strings w/o writing to streams.\n4. Was not weighed down with other unrelated baggage.\n\n## Functions\n\n### var code = consoleControl.up(_num = 1_)\n\nReturns the escape sequence to move _num_ lines up.\n\n### var code = consoleControl.down(_num = 1_)\n\nReturns the escape sequence to move _num_ lines down.\n\n### var code = consoleControl.forward(_num = 1_)\n\nReturns the escape sequence to move _num_ lines righ.\n\n### var code = consoleControl.back(_num = 1_)\n\nReturns the escape sequence to move _num_ lines left.\n\n### var code = consoleControl.nextLine(_num = 1_)\n\nReturns the escape sequence to move _num_ lines down and to the beginning of\nthe line.\n\n### var code = consoleControl.previousLine(_num = 1_)\n\nReturns the escape sequence to move _num_ lines up and to the beginning of\nthe line.\n\n### var code = consoleControl.eraseData()\n\nReturns the escape sequence to erase everything from the current cursor\nposition to the bottom right of the screen. This is line based, so it\nerases the remainder of the current line and all following lines.\n\n### var code = consoleControl.eraseLine()\n\nReturns the escape sequence to erase to the end of the current line.\n\n### var code = consoleControl.goto(_x_, _y_)\n\nReturns the escape sequence to move the cursor to the designated position. \nNote that the origin is _1, 1_ not _0, 0_.\n\n### var code = consoleControl.gotoSOL()\n\nReturns the escape sequence to move the cursor to the beginning of the\ncurrent line. (That is, it returns a carriage return, `\\r`.)\n\n### var code = consoleControl.beep()\n\nReturns the escape sequence to cause the termianl to beep. (That is, it\nreturns unicode character `\\x0007`, a Control-G.)\n\n### var code = consoleControl.hideCursor()\n\nReturns the escape sequence to hide the cursor.\n\n### var code = consoleControl.showCursor()\n\nReturns the escape sequence to show the cursor.\n\n### var code = consoleControl.color(_colors = []_)\n\n### var code = consoleControl.color(_color1_, _color2_, _…_, _colorn_)\n\nReturns the escape sequence to set the current terminal display attributes\n(mostly colors). Arguments can either be a list of attributes or an array\nof attributes. The difference between passing in an array or list of colors\nand calling `.color` separately for each one, is that in the former case a\nsingle escape sequence will be produced where as in the latter each change\nwill have its own distinct escape sequence. Each attribute can be one of:\n\n* Reset:\n * **reset** – Reset all attributes to the terminal default.\n* Styles:\n * **bold** – Display text as bold. In some terminals this means using a\n bold font, in others this means changing the color. In some it means\n both.\n * **italic** – Display text as italic. This is not available in most Windows terminals.\n * **underline** – Underline text. This is not available in most Windows Terminals.\n * **inverse** – Invert the foreground and background colors.\n * **stopBold** – Do not display text as bold.\n * **stopItalic** – Do not display text as italic.\n * **stopUnderline** – Do not underline text.\n * **stopInverse** – Do not invert foreground and background.\n* Colors:\n * **white**\n * **black**\n * **blue**\n * **cyan**\n * **green**\n * **magenta**\n * **red**\n * **yellow**\n * **grey** / **brightBlack**\n * **brightRed**\n * **brightGreen**\n * **brightYellow**\n * **brightBlue**\n * **brightMagenta**\n * **brightCyan**\n * **brightWhite**\n* Background Colors:\n * **bgWhite**\n * **bgBlack**\n * **bgBlue**\n * **bgCyan**\n * **bgGreen**\n * **bgMagenta**\n * **bgRed**\n * **bgYellow**\n * **bgGrey** / **bgBrightBlack**\n * **bgBrightRed**\n * **bgBrightGreen**\n * **bgBrightYellow**\n * **bgBrightBlue**\n * **bgBrightMagenta**\n * **bgBrightCyan**\n * **bgBrightWhite**\n\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+https://github.com/iarna/console-control-strings.git"
},
"scripts": {
"test": "standard && tap test/*.js"
},
"version": "1.1.0"
}
... ...
{
"asi": true,
"laxcomma": true,
"laxbreak": true,
"node": true,
"strict": false,
"es5": true
}
... ...
#IDE Support
.idea
#Project
.lock-wscript
*.dylib
*.so
*.o
*.lo
*.Makefile
*.target.gyp.mk
build
Release
Debug
node_modules
Makefile.gyp
gyp-*-tool
.dirstamp
npm-debug.log
... ...
os:
- linux
- osx
sudo: false
language: cpp
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- g++-4.8
env:
matrix:
- TRAVIS_NODE_VERSION="0.10"
- TRAVIS_NODE_VERSION="0.12"
- TRAVIS_NODE_VERSION="2"
- TRAVIS_NODE_VERSION="4.1"
- TRAVIS_NODE_VERSION="5.1"
- TRAVIS_NODE_VERSION="6"
install:
- rm -rf ~/.nvm && git clone https://github.com/creationix/nvm.git ~/.nvm && (cd ~/.nvm && git checkout `git describe --abbrev=0 --tags`) && source ~/.nvm/nvm.sh && nvm install $TRAVIS_NODE_VERSION
- if [[ $TRAVIS_OS_NAME == "linux" ]]; then export CXX=g++-4.8; fi
- $CXX --version
- PATH="`npm bin`:`npm bin -g`:$PATH"
# Node 0.8 comes with a too obsolete npm
- if [[ "`node --version`" =~ ^v0\.8\. ]]; then npm install -g npm@1.4.28 ; fi
# Install dependencies and build
- npm install
script:
# Output useful info for debugging
- node --version
- npm --version
# Run tests
- npm test
... ...
2.2.0 / 2016-10-29
==================
* [[`8fc355f276`](https://github.com/node-ffi/ffi/commit/8fc355f276)] - add libffi `version` string (Nathan Rajlich)
* [[`97d7ab12e6`](https://github.com/node-ffi/ffi/commit/97d7ab12e6)] - remove OS X 10.5 deployment target (Nathan Rajlich)
* [[`7a928f38b1`](https://github.com/node-ffi/ffi/commit/7a928f38b1)] - **test**: add a test case for [TooTallNate/ref#56](https://github.com/TooTallNate/ref/issues/56) (Nathan Rajlich)
2.1.0 / 2016-08-03
==================
* [[`a66fb8b282`](https://github.com/node-ffi/ffi/commit/a66fb8b282)] - rename History.md to CHANGELOG.md (Nathan Rajlich)
* [[`424d6b2278`](https://github.com/node-ffi/ffi/commit/424d6b2278)] - test node v6 with CI (Nathan Rajlich)
* [[`37dc33f10d`](https://github.com/node-ffi/ffi/commit/37dc33f10d)] - Move `errno` method implement to C++ side (Lee, SungUk)
* [[`f0547a7535`](https://github.com/node-ffi/ffi/commit/f0547a7535)] - **test**: use full URL to issue (Nathan Rajlich)
* [[`819c664605`](https://github.com/node-ffi/ffi/commit/819c664605)] - **appveyor, travis**: test node v5.1 (Nathan Rajlich)
* [[`b6e8dba046`](https://github.com/node-ffi/ffi/commit/b6e8dba046)] - remove benchmark files (Nathan Rajlich)
* [[`f5e445be91`](https://github.com/node-ffi/ffi/commit/f5e445be91)] - **test**: load Foundation first instead (Nathan Rajlich)
* [[`529ea78029`](https://github.com/node-ffi/ffi/commit/529ea78029)] - **travis**: remove iojs v3 (Nathan Rajlich)
* [[`c81ab1ed1e`](https://github.com/node-ffi/ffi/commit/c81ab1ed1e)] - **test**: load `Cocoa` lib for Obj-C tests (Nathan Rajlich)
* [[`829d7dac02`](https://github.com/node-ffi/ffi/commit/829d7dac02)] - **travis**: attempt to test "osx" (Nathan Rajlich)
* [[`979da99892`](https://github.com/node-ffi/ffi/commit/979da99892)] - **test**: fix hardcoded `strtoul()` bindings (Nathan Rajlich)
* [[`9cc558632c`](https://github.com/node-ffi/ffi/commit/9cc558632c)] - **test**: fix comment (Nathan Rajlich)
* [[`3d673ca2a1`](https://github.com/node-ffi/ffi/commit/3d673ca2a1)] - **test**: attempt to fix test 169 on Linux (Nathan Rajlich)
* [[`c2e5996d9d`](https://github.com/node-ffi/ffi/commit/c2e5996d9d)] - **test**: remove .only() (Nathan Rajlich)
* [[`1187b80f7b`](https://github.com/node-ffi/ffi/commit/1187b80f7b)] - **test**: add case for allowing Buffer backing store for "string" FFI argument (Nathan Rajlich)
* [[`3b09d1ac09`](https://github.com/node-ffi/ffi/commit/3b09d1ac09)] - **test**: remove semis (Nathan Rajlich)
* [[`74e29a17d0`](https://github.com/node-ffi/ffi/commit/74e29a17d0)] - **test**: whitespace fixes (Nathan Rajlich)
* [[`6551d4ab5b`](https://github.com/node-ffi/ffi/commit/6551d4ab5b)] - **appveyor**: test node v4.1 (Nathan Rajlich)
* [[`c0b64413fe`](https://github.com/node-ffi/ffi/commit/c0b64413fe)] - **travis**: test node v4.1 (Nathan Rajlich)
* [[`730bd4a92f`](https://github.com/node-ffi/ffi/commit/730bd4a92f)] - **travis**: drop "iojs-" prefix from version names (Nathan Rajlich)
* [[`0324f3be9c`](https://github.com/node-ffi/ffi/commit/0324f3be9c)] - test node v0.4 (Nathan Rajlich)
* [[`f3e393bb55`](https://github.com/node-ffi/ffi/commit/f3e393bb55)] - remove node v0.8 from testing matrices (Nathan Rajlich)
2.0.0 / 2015-09-04
==================
* update to "nan" v2, adds io.js v3 support
* replace "dlfcn-win32" with "simple-dlfcn-win32" (uses MIT license rather than LGPL, #226, @mcnameej)
* remove compiled binary file from libffi deps dir (#229, @fredericgermain)
* fix dynamic linking when locale is not English (#224, @unbornchikken)
* appveyor: test v0.8, io.js v2.5 and v3
* travis: test v0.8, and iojs v2.5 and v3
* package: add "license" field
* package: add Gábor to LICENSE and "contributors"
* package: move TooTallNate to "contributors" array
1.3.2 / 2015-07-31
==================
* package: made the nan dependency stricter (#217, @feldgendler)
* package: reflect the fact that the build fails for node <= 0.8 (#196, @addaleax)
1.3.1 / 2015-04-16
==================
* test: use `assert.throws()` for Obj-C test cases
* test: add case for #199 that covers callback and error propagation on non-libuv thread
* HandleScope issue fix for iojs v1.7+
* use Windows' native thread API, rather than libuv
1.3.0 / 2015-03-22
==================
* add appveyor.yml file for Windows testing
* add support for io.js >= v1.1.0 and node.js v0.12.x via nan
* avoid VS build error LNK2005
* package: allow any "debug" v2
* package: update github URLs for new repo location
* travis: don't test node v0.6, test v0.12
* now using libuv's pthread impl on Windows, removed `pthreads-win32` dep
* `dlfcn-win32` dep updated to fix process global symbols on Windows
* README: add appveyor build badge
* README: use SVG appveyor badge
1.2.7 / 2014-07-06
==================
* test: add test case for race condition in #153
* factorial: fix Windows build instructions
* example: turn factorial readme to Markdown
* example: add Windows libfactorial.dll compile command
* package: remove "expect.js" dev dependency
* test: remove final `expect.js` usage
* jshintrc: enable "laxbreak"
* travis: remove IRC notifications from Travis
* test: properly re-add Mocha's uncaught listeners
* test: add a try/catch test after the callback is GC'd
* src: fix race condition when callback is invoked from thread pool (@nikmikov, #154)
* change Node.js versions used on Travis CI for testing (@Mithgol, #151)
* use SVG to display Travis CI build testing status (@Mithgol, #149)
1.2.6 / 2013-10-08
==================
* just a minor documentation typo fix (Jason May, #126)
* example: fix "factorial" example on Windows (#127)
* package: add "keywords" section
* callback: store a reference to the CIF struct on the ffi closure Buffer instance (#125)
1.2.5 / 2013-04-06
==================
* type: make detecting "long" and "ulong" ffi_types work
* travis: don't test node v0.7.x, test node v0.10.x
1.2.4 / 2013-02-18
==================
* FreeBSD 32-bit support (Dave Osborne)
* libffi: don't build libffi as a "thin" archive (CentOS 5 support, #110)
1.2.3 / 2012-12-20
==================
* FreeBSD 64-bit support (Dave Osborne)
1.2.2 / 2012-12-15
==================
* fix nasty bug in async FFI'd function on node v0.9.x
1.2.1 / 2012-12-15
==================
* add node >= v0.9.4 support
1.2.0 / 2012-10-13
==================
* type: full support for "ref-array" arguments and return types
* type: add basic support for basic ref types without a `ffi_type` prop set
* don't call the "ref()" function on passed in arguments
* libffi: fix unused variable warnings
* add `Function` "type" for functions/callbacks that accept/return C Functions
* dynamic_library: use RTLD_LAZY by default
* export all the RTLD_* symbols from the native binding
* foreign_function: better error messages when a type's "set()" function throws
* callback: make catching callbacks that throw JS exceptions work as expected
* callback: more meaningful error message when a type's "set()" function throws
* callback: fix pointer return values
1.1.3 / 2012-09-25
==================
* callback: use `IsEmpty()` instead of an explicit NULL check
* test: use "bindings" to load the bindings for the variadic tests
* ffi: use HandleScope in WrapPointer() (fixes ffi calls in a tight loop, see #74)
* test: fix typo in test name
* libffi: disable the C4267 implicit conversion warnings on Windows
* libffi: remove "as.bat" from the gyp file
1.1.2 / 2012-09-16
==================
* callback: throw an Error if the callback function has been garbage collected
* test: 100% tests passing on Windows!
1.1.1 / 2012-09-16
==================
* libffi: define "FFI_MMAP_EXEC_WRIT" on OS X (#71)
* added a new test case that calls a callback function directly (#72)
1.1.0 / 2012-09-11
==================
* properly "gyp-ify" libffi
- added "libffi.gyp"
- no more "hacks" in binding.gyp
- no need for MozillaBuild on Windows anymore!
1.0.7 / 2012-08-03
==================
* export `FFI_FIRST_ABI`
* export abi_enum values for ARM processors (100% tests passing on Raspberry Pi!)
1.0.6 / 2012-07-22
==================
* VariadicForeignFunction: apply a tweak to prevent false positives on ffi id's
1.0.5 / 2012-07-22
==================
* DynamicLibrary: use 'string' instead of "char *"
* DynamicLibrary: set the "name" property of the returned Buffer when get() is called
* test: add some "DynamicLibrary" tests
* VariadicForeignFunction: quick hack fix for the key caching name collision
1.0.4 / 2012-07-12
==================
* exit early when not compiling from within a MozillaBuild window on Windows
1.0.3 / 2012-07-9
=================
* refactor the README
* fix deprecation warning for using the `Utf8String` type (renamed to `CString`)
* remove circular `require()` calls (Justin Freitag)
* use the node-gyp `--directory` flag for `npm test` command
1.0.2 / 2012-06-20
==================
* Fix Windows build (32-bit at least). Fixes #51.
1.0.1 / 2012-06-13
==================
* Refactor the variadic function generator to allow for an overridden "returnType"
1.0.0 / 2012-05-31
==================
* Add a `VariadicForeignFunction` function for vararg C functions
* Various cleanup
* Don't export the native bindings (`ffi.Bindings` is gone)
* Use the `ref()` function when available, then fall back to `ref.alloc()`
* Add a few more tests
1.0.0-alpha1 / 2012-05-29
=========================
* Readme improvements
* Node >= v0.7.9 compatability
1.0.0-alpha / 2012-05-25
========================
* Alpha release of v1.0.0
< 1.0.0
=======
* Prehistoric: see `git log`
... ...
Copyright (c) 2009-2011 Richard "Rick" W. Branson
Copyright (c) 2012-2014 Nathan Rajlich, Richard "Rick" W. Branson
Copyright (c) 2015 Nathan Rajlich, Richard "Rick" W. Branson, Gabor Mezo
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.
... ...
node-ffi
========
### Node.js Foreign Function Interface
[![Build Status](https://travis-ci.org/node-ffi/node-ffi.svg?branch=master)](https://travis-ci.org/node-ffi/node-ffi)
[![Build Status](https://ci.appveyor.com/api/projects/status/n81apam1igfw8491?svg=true)](https://ci.appveyor.com/project/TooTallNate/node-ffi)
`node-ffi` is a Node.js addon for loading and calling dynamic libraries using
pure JavaScript. It can be used to create bindings to native libraries without
writing any C++ code.
It also simplifies the augmentation of node.js with C code as it takes care of
handling the translation of types across JavaScript and C, which can add reams
of boilerplate code to your otherwise simple C. See the `example/factorial`
for an example of this use case.
**WARNING**: node-ffi assumes you know what you're doing. You can pretty easily
create situations where you will segfault the interpreter and unless you've got
C debugger skills, you probably won't know what's going on.
Example
-------
``` js
var ffi = require('ffi');
var libm = ffi.Library('libm', {
'ceil': [ 'double', [ 'double' ] ]
});
libm.ceil(1.5); // 2
// You can also access just functions in the current process by passing a null
var current = ffi.Library(null, {
'atoi': [ 'int', [ 'string' ] ]
});
current.atoi('1234'); // 1234
```
For a more detailed introduction, see the [node-ffi tutorial page][tutorial].
Requirements
------------
* Linux, OS X, Windows, or Solaris.
* `libffi` comes bundled with node-ffi; it does *not* need to be installed on your system.
* The current version is tested to run on node v0.6, v0.8, v0.9 and v0.10.
Installation
------------
Make sure you've installed all the [necessary build
tools](https://github.com/TooTallNate/node-gyp#installation) for your platform,
then invoke:
``` bash
$ npm install ffi
```
Source Install / Manual Compilation
-----------------------------------
To compile from source it's easiest to use
[`node-gyp`](https://github.com/TooTallNate/node-gyp):
``` bash
$ npm install -g node-gyp
```
Now you can compile `node-ffi`:
``` bash
$ git clone git://github.com/node-ffi/node-ffi.git
$ cd node-ffi
$ node-gyp rebuild
```
Types
-----
The types that you specify in function declarations correspond to ref's types
system. So [see its docs][ref-types] for
a reference if you are unfamiliar.
V8 and 64-bit Types
-------------------
Internally, V8 stores integers that will fit into a 32-bit space in a 32-bit
integer, and those that fall outside of this get put into double-precision
floating point numbers. This is problematic because FP numbers are imprecise.
To get around this, the methods in node-ffi that deal with 64-bit integers return
strings and can accept strings as parameters.
Call Overhead
-------------
There is non-trivial overhead associated with FFI calls. Comparing a hard-coded
binding version of `strtoul()` to an FFI version of `strtoul()` shows that the
native hard-coded binding is orders of magnitude faster. So don't just use the
C version of a function just because it's faster. There's a significant cost in
FFI calls, so make them worth it.
License
-------
MIT License. See the `LICENSE` file.
[v1apichanges]: https://github.com/node-ffi/node-ffi/wiki/API-changes-from-v0.x-to-v1.x
[tutorial]: https://github.com/node-ffi/node-ffi/wiki/Node-FFI-Tutorial
[ref-types]: https://github.com/TooTallNate/ref#built-in-types
... ...
# http://www.appveyor.com/docs/appveyor-yml
# Test against these versions of Node.js.
environment:
# Visual Studio Version
MSVS_VERSION: 2013
# Test against these versions of Node.js and io.js
matrix:
# node.js
- nodejs_version: "0.10"
- nodejs_version: "0.12"
# io.js
- nodejs_version: "2"
- nodejs_version: "3.2"
- nodejs_version: "4.1"
- nodejs_version: "5.1"
- nodejs_version: "6"
platform:
- x86
- x64
# Install scripts. (runs after repo cloning)
install:
# Get the latest stable version of Node 0.STABLE.latest
- ps: if($env:nodejs_version -eq "0.8") {Install-Product node $env:nodejs_version}
- ps: if($env:nodejs_version -ne "0.8") {Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)}
# Node 0.8 comes with a too obsolete npm
- IF %nodejs_version% == 0.8 (npm install -g npm@1.4.28)
# Install latest NPM only for node.js versions until built in node-gyp adds io.js support
# Update is required for node.js 0.8 because built in npm(node-gyp) does not know VS2013
- IF %nodejs_version% LSS 1 (npm install -g npm@2)
- IF %nodejs_version% LSS 1 set PATH=%APPDATA%\npm;%PATH%
# Typical npm stuff.
- npm install --msvs_version=%MSVS_VERSION%
# Post-install test scripts.
test_script:
# Output useful info for debugging.
- node --version
- npm --version
# run tests
- npm test
# Don't actually build.
build: off
# Set build version format here instead of in the admin panel.
version: "{build}"
... ...
{
'targets': [
{
'target_name': 'ffi_bindings',
'sources': [
'src/ffi.cc'
, 'src/callback_info.cc'
, 'src/threaded_callback_invokation.cc'
],
'include_dirs': [
'<!(node -e "require(\'nan\')")'
],
'dependencies': [
'deps/libffi/libffi.gyp:ffi'
],
'conditions': [
['OS=="win"', {
'sources': [
'src/win32-dlfcn.cc'
],
}],
['OS=="mac"', {
'xcode_settings': {
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
'OTHER_CFLAGS': [
'-ObjC++'
]
},
'libraries': [
'-lobjc'
],
}]
]
}
]
}
... ...
.libs
.deps
*.o
*.lo
.dirstamp
*.la
*.pdb
*.obj
Makefile
config.log
config.status
*~
libffi.pc
libtool
stamp-h1
libffi*gz
autom4te.cache
... ...
此 diff 太大无法显示。