本片章节主要介绍多个关于c++ native addon可能用到的工具,其中,大部分都是node的工具,对于实现和使用native addon插件很有帮助。

Glob

按照自定义规则寻找文件

  1. $ npm i glob
var glob = require("glob")

// options is optional
glob("**/*.js", options, function (er, files) {
  // files is an array of filenames.
  // If the `nonull` option is set, and nothing
  // was found, then files is ["**/*.js"]
  // er is an error object or null.
})

bluebird

功能强大的 Promise 库,具有无与伦比的性能;

$ npm install bluebird

Then:

var Promise = require("bluebird");

Alternatively in ES6

import * as Promise from "bluebird";

If that ES6 import doesn’t work

import {Promise} from "bluebird";

node-bindings

帮助程序模块,用于加载 native modules.node 文件。
在Node的本机附加组件历史的整个过程中,依赖于所使用的构建工具和节点的版本,最终已在各种不同的位置编译了附加组件。更糟的是,现在gyp生成工具可以生成Release或Debug生成,每种版本都构建在不同的位置。
此模块检查将在其上构建本机插件的所有可能位置,并返回成功加载的第一个。

$ npm install --save bindings
var bindings = require('bindings')('binding.node')

// Use your bindings defined in your C files
bindings.your_c_function()

Download

下载并解压缩文件

$ npm install download
const fs = require('fs');
const download = require('download');

(async () => {
    await download('http://unicorn.com/foo.jpg', 'dist');

    fs.writeFileSync('dist/foo.jpg', await download('http://unicorn.com/foo.jpg'));

    download('unicorn.com/foo.jpg').pipe(fs.createWriteStream('dist/foo.jpg'));

    await Promise.all([
        'unicorn.com/foo.jpg',
        'cats.com/dancing.gif'
    ].map(url => download(url, 'dist')));
})();

extract-zip

用纯JavaScript编写的邮政编码提取。将zip解压缩到目录中。

$ npm install extract-zip --save
const extract = require('extract-zip')

async main () {
  try {
    await extract(source, { dir: target })
    console.log('Extraction complete')
  } catch (err) {
    // handle any errors
  }
}

node-fs-extra

Node.js:fs对象的额外方法,例如copy(),remove(),mkdirs()

$ npm install fs-extra
// You don't ever need to include the original fs module again:
// this is no longer necessary
const fs = require('fs')
// you can now do this:
const fs = require('fs-extra')

// Async with promises:
fs.copy('/tmp/myfile', '/tmp/mynewfile')
  .then(() => console.log('success!'))
  .catch(err => console.error(err))

// Async with callbacks:
fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
  if (err) return console.error(err)
  console.log('success!')
})

// Sync:
try {
  fs.copySync('/tmp/myfile', '/tmp/mynewfile')
  console.log('success!')
} catch (err) {
  console.error(err)
}

// Async/Await:
async function copyFiles () {
  try {
    await fs.copy('/tmp/myfile', '/tmp/mynewfile')
    console.log('success!')
  } catch (err) {
    console.error(err)
  }
}

copyFiles()

Just

Just是一个库,用于组织JS项目的构建任务。它包括

  • 构建任务构建定义库
  • 具有TypeScript,Webpack和jest的节点和浏览器项目的合理的预设构建流程
  • 项目脚手架工具,可生成无需弹出的仓库,可跟踪模板更改
    $ npm i -D just-scripts
    
    ```javascript const { task, option, logger, argv } = require(‘just-scripts’);

option(‘name’, { default: ‘world’ });

task(‘sayhello’, function() { logger.info(argv().name); });

Then run it! It is best to either place `just` inside a npm run script or run it with `npx`:
```bash
$ npx just sayhello
$ npx just sayhello --name me

Lodash.isEqual

在两个值之间进行深度比较以确定它们是否等效。

var object = { 'a': 1 };
var other = { 'a': 1 };

_.isEqual(object, other);
// => true

object === other;
// => false

NAN

由于V8(以及Node内核中的某些功能)中的疯狂更改,保持本地插件在各个版本之间(尤其是0.10到0.12到4.0)之间愉快地编译是一个小小的噩梦。 该项目的目标是存储开发本机Node.js插件所需的所有逻辑,而不必检查NODE_MODULE_VERSION并使自己陷入宏观困境。
该项目还包含一些帮助程序实用程序,这些程序使附加组件的开发更加愉快。

$ npm install --save nan

Pull in the path to NAN in your binding.gyp so that you can use #include in your .cpp files:

"include_dirs" : [
    "<!(node -e "require('nan')")"
]

This works like a -I when compiling your addon.

rimraf

A rm -rf util for nodejs

$ npm install rimraf

rimraf(f, [opts], callback)

shelljs

Node Node.js的可移植Unix shell命令

$ npm install [-g] shelljs
var shell = require('shelljs');

if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git');
  shell.exit(1);
}

// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');

// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
  shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
  shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
  shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');

// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
  shell.echo('Error: Git commit failed');
  shell.exit(1);
}

yuv-buffer

YUV图像帧缓冲区可帮助JavaScript实用程序
平面YUV图像帧代表通常用于视频处理以及视频和图像压缩的YUV颜色空间中的彩色图像。
Y或“ luma”平面保存亮度值,而U和V“ chroma”平面存储蓝色和红色分量的颜色“偏移”
通常必须将YUV图像转换为RGB或从RGB转换为实际的捕获和显示。有关在浏览器中显示YUV帧的信息,请参见yuv-canvas模块;有关完整的浏览器内视频解码器/播放器,请参见ogv.js

$ npm install yuv-buffer
var YUVBuffer = require("yuv-buffer.js");

var YUVBuffer = require("yuv-buffer.js");

// HDTV 1080p:
var format = {
  // Many video formats require an 8- or 16-pixel block size.
  width: 1920,
  height: 1088,

  // Using common 4:2:0 layout, chroma planes are halved in each dimension.
  chromaWidth: 1920 / 2,
  chromaHeight: 1088 / 2,

  // Crop out a 1920x1080 visible region:
  cropLeft: 0,
  cropTop: 4,
  cropWidth: 1920,
  cropHeight: 1080,

  // Square pixels, so same as the crop size.
  displayWidth: 1920,
  displayHeight: 1080
};

var format = YUVBuffer.format(format);

yuv-canvas

YUVCanvas将YUV视频帧绘制到HTML 5 canvas元素。
它用于ogv.js媒体播放器,适用于使用WebGL进行绘图和色彩空间转换的高频帧更新。

可以在支持的浏览器(适用于iOS 8和OS X 10.9的Firefox,Chrome,IE 11,Edge和Safari)上使用WebGL来完成YCbCr-> RGB的加速转换和绘制,并且默认情况下启用(如果可用)。

调用者可以将’webGL:false’键传递给选项以强制使用软件转换和2d canvas,或者将’webGL:true’传递给WebGL初始化失败的失败。

yuv-canvas旨在通过browserify,webpack或类似的npm友好捆绑工具使用。

var YUVCanvas = require('yuv-canvas');

// Get your canvas
var canvas = document.querySelector('canvas#myvid');

// Attach it to a YUVCanvas.FrameSink instance!
//
// This will take over the canvas drawing context, which may include switching
// it into WebGL mode or resizing it to fit the output frames. From now on you
// can manipulate the canvas element itself such as attaching it in the DOM or
// changing its CSS styles, but should not attempt to touch its size or drawing
// context directly.
var yuv = YUVCanvas.attach(canvas);

// Now... given a YUV frame buffer object, draw it!
var buffer = decodeVideoFrame();
yuv.drawFrame(buffer);

// Or clear the canvas.
yuv.clear();

ogv.js

使用Ogg / Vorbis / Theora / Opus / WebM库和Emscripten编译的JavaScript媒体播放器
基于libogg,libvorbis,libtheora,libopus,libvpx,libnestegg和dav1d编译为带有Emscripten的JavaScript和WebAssembly。
demo: https://brionv.com/misc/ogv.js/demo/

$ npm install ogv

OGVPlayer类实现一个播放器,并支持HTMLMediaElement和HTMLVideoElement中事件,属性和方法的子集。

var ogv = require('ogv');

// Access public classes either as ogv.OGVPlayer or just OGVPlayer.
// Your build/lint tools may be happier with ogv.OGVPlayer!
ogv.OGVLoader.base = '/path/to/resources';
var player = new ogv.OGVPlayer();
  // Create a new player with the constructor
  var player = new OGVPlayer();

  // Or with options
  var player = new OGVPlayer({
    debug: true,
    debugFilter: /demuxer/
  });

  // Now treat it just like a video or audio element
  containerElement.appendChild(player);
  player.src = 'path/to/media.ogv';
  player.play();
  player.addEventListener('ended', function() {
    // ta-da!
  });

assert

javascript的简单断言库;
目标是提供一个在功能上与Node.js断言API尽可能相同的API。阅读API文档的官方文档

$ npm install assert