JS在线运行

版本:

所属目录
点击了解高性能代码运行API
运行结果
教程手册
代码仓库
极速运行
终端运行
图形+终端

                        
以下是用户最新保存的代码
中英文混合排序 发布于:2024-04-24 17:25 测试html代码转义 发布于:2024-04-24 16:27 hljs 测试 发布于:2024-04-24 11:34 bms规则链经纬度转换2 发布于:2024-04-23 17:51 2024各乡镇单位排名 发布于:2024-04-21 21:31 2024年各乡镇单位排名情况 发布于:2024-04-21 21:06 驾驶舱默认初始化 发布于:2024-04-19 15:05 with+new Function实现js沙箱 发布于:2024-04-18 18:10 深拷贝原理解析 发布于:2024-04-15 18:01 递归课程表 发布于:2024-04-15 17:49 promise.all 捕获某一个错误 发布于:2024-04-15 17:29 这是用于学习js代码的demo 发布于:2024-04-15 16:47 JS 数组 详解 发布于:2024-04-14 13:02 按比例分钱 发布于:2024-04-12 11:31 根据路径生成路由2 发布于:2024-04-11 09:23 select过滤函数 发布于:2024-04-10 13:17 腾讯云cos签名 发布于:2024-04-10 09:51 百度文心评论 发布于:2024-04-09 15:05 根据路径生成路由 发布于:2024-04-11 09:23 从原型修改闭包 发布于:2024-04-11 13:59 大写字母、小写字母、数字、特殊字符,并且长度8及位以上、不能有连续数字和字母 发布于:2024-03-29 17:06 ## 截取下标0到第2个“-”间字符串 发布于:2024-03-29 08:54 基于区块链的数字身份系统的设计与实现 发布于:2024-03-21 19:56 模版引擎简单方案 发布于:2024-03-21 17:26 array filter 发布于:2024-03-21 13:53 模版引擎解析 发布于:2024-03-20 21:08 列表转树的方案 发布于:2024-03-20 20:27 排序算法介绍 发布于:2024-03-20 13:40 处理数据demo 20240318 发布于:2024-03-19 14:42 面试遇到的题目 发布于:2024-03-19 11:25 测试代码。 发布于:2024-03-19 00:52 快速排序的算法 发布于:2024-03-19 00:49 我的联系代码 发布于:2024-03-18 23:13 思迅天店程序易用修改 发布于:2024-03-19 00:42 数组统计同一id数量 发布于:2024-03-17 21:32 手写promise 发布于:2024-03-17 00:13 1. 数据排序 假设有如下字符串“A12”,其中“A”表示数据类型(A-Z),“12”表示数据序号(0-9)。 现在需要对一组数据先按照数据序号再按照数据类型进行排序。 例如:["B3","D2","F1","A9","D12","A2","C1","Z0","B1"]=>["Z0","B1","C1","F1","A2","D2","B3","A9","D12"] 发布于:2024-03-15 23:50 BMS经纬度变更 发布于:2024-04-23 17:31 继承: 原型继承 1.定义父类型构造函数 2.给父类型的原型添加方法 3.定义子类型的构造函数 4.创建父类型的对象赋值给子类型的原型 5.将子类型原型的构造属性设置为子类型 6.给子类型原型添加方法 7.创建子类型的对象: 可以调用父类型的方法 来自http://t.csdnimg.cn/ToxNF 发布于:2024-03-14 16:39 编辑文件夹树结构,过滤树里面数组为空值 发布于:2024-03-12 16:02 转化为json文件 发布于:2024-03-08 13:55 Three.js示例 发布于:2024-03-08 09:51 qs示例代码 发布于:2024-03-04 15:08 接龙拆解,获取总数。 发布于:2024-03-04 10:16 ## NuanXinPro 在线编辑 发布于:2024-03-04 09:49 国科大csv课表获取 发布于:2024-03-03 15:35 reduce 使用 发布于:2024-03-01 16:21 测试所用的 发布于:2024-02-28 21:21 promise.all调用案例 发布于:2024-02-27 15:56 保存测试nodejs 事件的6个阶段执行逻辑 发布于:2024-02-23 21:29 [更多]
显示目录

C/C++ 插件



学习嵌入式的绝佳套件,esp8266开源小电视成品,比自己去买开发板+屏幕还要便宜,省去了焊接不当搞坏的风险。 蜂鸣版+触控升级仅36元,更强的硬件、价格全网最低。

点击购买 固件广场

C/C++ 插件

Node.js Addons(插件)是动态链接的共享对象。他提供了C/C++类库能力。这些API比较复杂,他包以下几个类库:

  • V8 JavaScript, C++类库。用来和JavaScript交互,比如创建对象,调用函数等等。

  • libuv,C事件循环库。等待文件描述符变为可读,等待定时器,等待信号时,会和libuv打交道。或者说,如果你需要和I/O打交道,就会用到libuv。

  • 内部Node类库。其中最重要的类node::ObjectWrap,你会经常派生自它。

Node已经将所有的依赖编译成可以执行文件,所以你不必当心这些类库的链接问题。

Hello world

现在我们来写一个C++插件的小例子,它的效果和以下JS代码一致:

module.exports.hello = function() { return 'world'; };

通过以下代码来创建hello.cc文件:

// hello.cc
#include  <node.h>

using namespace v8;

void  Method(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}

void  init(Handle<Object> exports) {
  NODE_SET_METHOD(exports, "hello", Method);
}

NODE_MODULE(addon, init)

注意:所有的Node插件必须输出一个初始化函数:

void Initialize (Handle<Object> exports);
NODE_MODULE(module_name, Initialize)

NODE_MODULE 之后的代码没有分号,因为它不是一个函数 (参见 node.h )。

module_name 必须和二进制文件名字一致 (后缀是.node)。

源文件会编译成 addon.node 二进制插件。为此我们创建了一个很像JSON的 binding.gyp 文件,它包含配置信息,这个文件用node-gyp编译。

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "hello.cc" ]
    }
  ]
}

下一步创建一个 node-gyp configure 工程,在平台上生成这些文件。

创建后,在 build/ 文件夹里拥有一个 Makefile (Unix系统) 文件或者 vcxproj 文件(Windows 系统)。接着调用 node-gyp build 命令编译,生成 .node 文件。这些文件位于 build/Release/ 目录里。

现在,你能在Node工程中使用这些二进制扩展插件,在 hello.js 中声明 require 之前编译的 hello.node :

// hello.js
var addon = require('./build/Release/addon');

console.log(addon.hello()); // 'world'

插件模式

下面是一些addon插件的模式,帮助你开始编码。v8 reference文档里包含v8的各种接口,Embedder's Guide这个文档包含各种说明,比如handles, scopes, function templates等等。

在使用这些例子前,你需要先用node-gyp编译。创建binding.gyp 文件:

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "addon.cc" ]
    }
  ]
}

将文件名加入到sources数组里就可以使用多个.cc文件,例如 :

"sources": ["addon.cc", "myexample.cc"]

准备好binding.gyp文件后, 你就能配置并编译插件:

$ node-gyp configure build

函数参数

从以下模式中解释了如何从JavaScript函数中读取参数,并返回结果。仅需要一个addon.cc文件:

// addon.cc
#include <node.h>

using namespace v8;

void Add(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  if (args.Length() < 2) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong number of arguments")));
    return;
  }

  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }

  double value = args[0]->NumberValue() + args[1]->NumberValue();
  Local<Number> num = Number::New(isolate, value);

  args.GetReturnValue().Set(num);
}

void Init(Handle<Object> exports) {
  NODE_SET_METHOD(exports, "add", Add);
}

NODE_MODULE(addon, Init)

可以用以下的JavaScript代码片段测试:

// test.js
var addon = require('./build/Release/addon');

console.log( 'This should be eight:', addon.add(3,5) );

回调Callbacks

你也能传JavaScript函数给C++函数,并执行它。在addon.cc中:

// addon.cc
#include  <node.h>

using namespace v8;

void  RunCallback(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  Local<Function> cb = Local<Function>::Cast(args[0]);
  const unsigned argc = 1;
  Local<Value> argv[argc] = { String::NewFromUtf8(isolate, "hello world") };
  cb->Call(isolate->GetCurrentContext()->Global(), argc, argv);
}

void  Init(Handle<Object> exports, Handle<Object> module) {
  NODE_SET_METHOD(module, "exports", RunCallback);
}

NODE_MODULE(addon, Init)

注意,这个例子中使用了Init()里的2个参数,module对象是第二个参数。它允许addon使用一个函数完全重写exports。

可以用以下的代码来测试:

// test.js
var addon = require('./build/Release/addon');

addon(function(msg){
  console.log(msg); // 'hello world'
});

对象工厂

在addon.cc模式里,你能用C++函数创建并返回一个新的对象,这个对象所包含的msg属性是由createObject()函数传入:

// addon.cc
#include  <node.h>

using namespace v8;

void  CreateObject(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  Local<Object> obj = Object::New(isolate);
  obj->Set(String::NewFromUtf8(isolate, "msg"), args[0]->ToString());

  args.GetReturnValue().Set(obj);
}

void  Init(Handle<Object> exports, Handle<Object> module) {
  NODE_SET_METHOD(module, "exports", CreateObject);
}

NODE_MODULE(addon, Init)

使用JavaScript测试:

// test.js
var addon = require('./build/Release/addon');

var obj1 = addon('hello');
var obj2 = addon('world');
console.log(obj1.msg+' '+obj2.msg); // 'hello world'

工厂模式

这个模式里展示了如何创建并返回一个JavaScript函数,它是由C++函数包装的 :

// addon.cc
#include  <node.h>

using namespace v8;

void  MyFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world"));
}

void  CreateFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
  Local<Function> fn = tpl->GetFunction();

  // omit this to make it anonymous
  fn->SetName(String::NewFromUtf8(isolate, "theFunction"));

  args.GetReturnValue().Set(fn);
}

void  Init(Handle<Object> exports, Handle<Object> module) {
  NODE_SET_METHOD(module, "exports", CreateFunction);
}

NODE_MODULE(addon, Init)

测试:

// test.js
var addon = require('./build/Release/addon');

var fn = addon();
console.log(fn()); // 'hello world'

包装C++对象

以下会创建一个C++对象的包装MyObject,这样他就能在JavaScript中用new实例化。首先在addon.cc中准备主要模块:

// addon.cc
#include  <node.h>
#include  "myobject.h"

using namespace v8;

void  InitAll(Handle<Object> exports) {
  MyObject::Init(exports);
}

NODE_MODULE(addon, InitAll)

接着在myobject.h创建包装,它继承自node::ObjectWrap:

// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include  <node.h>
#include  <node_object_wrap.h>

class MyObject : public node::ObjectWrap {
 public:
  static  void  Init(v8::Handle<v8::Object> exports);

 private:
  explicit  MyObject(double value = 0);
  ~MyObject();

  static  void  New(const v8::FunctionCallbackInfo<v8::Value>& args);
  static  void  PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
  static v8::Persistent<v8::Function> constructor;
  double value_;
};

#endif

在myobject.cc中实现各种暴露的方法,通过给构造函数添加prototype属性来暴露plusOne方法:

// myobject.cc
#include "myobject.h"

using namespace v8;

Persistent<Function> MyObject::constructor;

MyObject::MyObject(double value) : value_(value) {
}

MyObject::~MyObject() {
}

void MyObject::Init(Handle<Object> exports) {
  Isolate* isolate = Isolate::GetCurrent();

  // Prepare constructor template
  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
  tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  // Prototype
  NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);

  constructor.Reset(isolate, tpl->GetFunction());
  exports->Set(String::NewFromUtf8(isolate, "MyObject"),
               tpl->GetFunction());
}

void MyObject::New(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new MyObject(...)`
    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
    MyObject* obj = new MyObject(value);
    obj->Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `MyObject(...)`, turn into construct call.
    const int argc = 1;
    Local<Value> argv[argc] = { args[0] };
    Local<Function> cons = Local<Function>::New(isolate, constructor);
    args.GetReturnValue().Set(cons->NewInstance(argc, argv));
  }
}

void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());
  obj->value_ += 1;

  args.GetReturnValue().Set(Number::New(isolate, obj->value_));
}

测试:

// test.js
var addon = require('./build/Release/addon');

var obj = new addon.MyObject(10);
console.log( obj.plusOne() ); // 11
console.log( obj.plusOne() ); // 12
console.log( obj.plusOne() ); // 13

包装对象工厂

当你想创建本地对象,又不想在JavaScript中严格的使用new初始化的时候,以下方法非常实用:

var obj = addon.createObject();
// instead of:
// var obj = new addon.Object();

addon.cc中注册createObject方法:

// addon.cc
#include  <node.h>
#include  "myobject.h"

using namespace v8;

void  CreateObject(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
  MyObject::NewInstance(args);
}

void  InitAll(Handle<Object> exports, Handle<Object> module) {
  MyObject::Init();

  NODE_SET_METHOD(module, "exports", CreateObject);
}

NODE_MODULE(addon, InitAll)

在myobject.h中有静态方法NewInstance,他能实例化对象(它就像JavaScript的new):

// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include  <node.h>
#include  <node_object_wrap.h>

class MyObject : public node::ObjectWrap {
 public:
  static  void  Init();
  static  void  NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);

 private:
  explicit  MyObject(double value = 0);
  ~MyObject();

  static  void  New(const v8::FunctionCallbackInfo<v8::Value>& args);
  static  void  PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
  static v8::Persistent<v8::Function> constructor;
  double value_;
};

#endif

这个实现方法和myobject.cc类似:

// myobject.cc
#include <node.h>
#include "myobject.h"

using namespace v8;

Persistent<Function> MyObject::constructor;

MyObject::MyObject(double value) : value_(value) {
}

MyObject::~MyObject() {
}

void MyObject::Init() {
  Isolate* isolate = Isolate::GetCurrent();
  // Prepare constructor template
  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
  tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  // Prototype
  NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);

  constructor.Reset(isolate, tpl->GetFunction());
}

void MyObject::New(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new MyObject(...)`
    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
    MyObject* obj = new MyObject(value);
    obj->Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `MyObject(...)`, turn into construct call.
    const int argc = 1;
    Local<Value> argv[argc] = { args[0] };
    Local<Function> cons = Local<Function>::New(isolate, constructor);
    args.GetReturnValue().Set(cons->NewInstance(argc, argv));
  }
}

void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  const unsigned argc = 1;
  Handle<Value> argv[argc] = { args[0] };
  Local<Function> cons = Local<Function>::New(isolate, constructor);
  Local<Object> instance = cons->NewInstance(argc, argv);

  args.GetReturnValue().Set(instance);
}

void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());
  obj->value_ += 1;

  args.GetReturnValue().Set(Number::New(isolate, obj->value_));
}

测试:

// test.js
var createObject = require('./build/Release/addon');

var obj = createObject(10);
console.log( obj.plusOne() ); // 11
console.log( obj.plusOne() ); // 12
console.log( obj.plusOne() ); // 13

var obj2 = createObject(20);
console.log( obj2.plusOne() ); // 21
console.log( obj2.plusOne() ); // 22
console.log( obj2.plusOne() ); // 23

传递包装对象

除了包装并返回C++对象,你可以使用Node的node::ObjectWrap::Unwrap帮助函数来解包。在下面的addon.cc中,我们介绍了一个add()函数,它能获取2个 MyObject对象:

// addon.cc
#include  <node.h>
#include  <node_object_wrap.h>
#include  "myobject.h"

using namespace v8;

void  CreateObject(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);
  MyObject::NewInstance(args);
}

void  Add(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(
      args[0]->ToObject());
  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(
      args[1]->ToObject());

  double sum = obj1->value() + obj2->value();
  args.GetReturnValue().Set(Number::New(isolate, sum));
}

void  InitAll(Handle<Object> exports) {
  MyObject::Init();

  NODE_SET_METHOD(exports, "createObject", CreateObject);
  NODE_SET_METHOD(exports, "add", Add);
}

NODE_MODULE(addon, InitAll)

介绍myobject.h里的一个公开方法,它能在解包后使用私有变量:

// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include  <node.h>
#include  <node_object_wrap.h>

class MyObject : public node::ObjectWrap {
 public:
  static  void  Init();
  static  void  NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);
  inline  double  value()  const { return value_; }

 private:
  explicit  MyObject(double value = 0);
  ~MyObject();

  static  void  New(const v8::FunctionCallbackInfo<v8::Value>& args);
  static v8::Persistent<v8::Function> constructor;
  double value_;
};

#endif

myobject.cc的实现方法和之前的类似:

// myobject.cc
#include <node.h>
#include "myobject.h"

using namespace v8;

Persistent<Function> MyObject::constructor;

MyObject::MyObject(double value) : value_(value) {
}

MyObject::~MyObject() {
}

void MyObject::Init() {
  Isolate* isolate = Isolate::GetCurrent();

  // Prepare constructor template
  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
  tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  constructor.Reset(isolate, tpl->GetFunction());
}

void MyObject::New(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new MyObject(...)`
    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
    MyObject* obj = new MyObject(value);
    obj->Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `MyObject(...)`, turn into construct call.
    const int argc = 1;
    Local<Value> argv[argc] = { args[0] };
    Local<Function> cons = Local<Function>::New(isolate, constructor);
    args.GetReturnValue().Set(cons->NewInstance(argc, argv));
  }
}

void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = Isolate::GetCurrent();
  HandleScope scope(isolate);

  const unsigned argc = 1;
  Handle<Value> argv[argc] = { args[0] };
  Local<Function> cons = Local<Function>::New(isolate, constructor);
  Local<Object> instance = cons->NewInstance(argc, argv);

  args.GetReturnValue().Set(instance);
}

测试:

// test.js
var addon = require('./build/Release/addon');

var obj1 = addon.createObject(10);
var obj2 = addon.createObject(20);
var result = addon.add(obj1, obj2);

console.log(result); // 30
由JSRUN为你提供的JS在线运行、在线编译工具
        JSRUN提供的JS 在线运行,JS 在线运行工具,基于linux操作系统环境提供线上编译和线上运行,具有运行快速,运行结果与常用开发、生产环境保持一致的特点。
yout