nodejs callback

doc: http://docs.libuv.org/
Read this book : http://nikhilm.github.io/uvbook/index.html

Use uv_async_init() and uv_async_send(). You can attach your own data pointer to the uv_async_t's data member (e.g. uv_async_t foo; foo.data = someptr;). This is where you could store any data you need (e.g. information about the enumerated windows in your case) when signalling the main thread with uv_async_send().

Once inside the uv_async callback on the main thread, you can read from the same data member and call to to javascript with the v8 API.

nodejs fs impl:

class FSReqWrap: public ReqWrap<uv_fs_t> {
 public:
  void* operator new(size_t size) { return new char[size]; }
  void* operator new(size_t size, char* storage) { return storage; }

  FSReqWrap(Environment* env, const char* syscall, char* data = NULL)
    : ReqWrap<uv_fs_t>(env, Object::New(env->isolate())),
      syscall_(syscall),
      data_(data),
      dest_len_(0) {
  }

  void ReleaseEarly() {
    if (data_ == NULL)
      return;
    delete[] data_;
    data_ = NULL;
  }

  inline const char* syscall() const { return syscall_; }
  inline const char* dest() const { return dest_; }
  inline unsigned int dest_len() const { return dest_len_; }
  inline void dest_len(unsigned int dest_len) { dest_len_ = dest_len; }

 private:
  const char* syscall_;
  char* data_;
  unsigned int dest_len_;
  char dest_[1];
};


#define ASSERT_OFFSET(a) \
  if (!(a)->IsUndefined() && !(a)->IsNull() && !IsInt64((a)->NumberValue())) { \
    return env->ThrowTypeError("Not an integer"); \
  }
#define ASSERT_TRUNCATE_LENGTH(a) \
  if (!(a)->IsUndefined() && !(a)->IsNull() && !IsInt64((a)->NumberValue())) { \
    return env->ThrowTypeError("Not an integer"); \
  }
#define GET_OFFSET(a) ((a)->IsNumber() ? (a)->IntegerValue() : -1)
#define GET_TRUNCATE_LENGTH(a) ((a)->IntegerValue())

static inline bool IsInt64(double x) {
  return x == static_cast<double>(static_cast<int64_t>(x));
}


static void After(uv_fs_t *req) {
  FSReqWrap* req_wrap = static_cast<FSReqWrap*>(req->data);
  assert(&req_wrap->req_ == req);
  req_wrap->ReleaseEarly();  // Free memory that's no longer used now.

  Environment* env = req_wrap->env();
  HandleScope handle_scope(env->isolate());
  Context::Scope context_scope(env->context());

  // there is always at least one argument. "error"
  int argc = 1;

  // Allocate space for two args. We may only use one depending on the case.
  // (Feel free to increase this if you need more)
  Local<Value> argv[2];

  if (req->result < 0) {
    // If the request doesn't have a path parameter set.
    if (req->path == NULL) {
      argv[0] = UVException(req->result, NULL, req_wrap->syscall());
    } else if ((req->result == UV_EEXIST ||
                req->result == UV_ENOTEMPTY ||
                req->result == UV_EPERM) &&
               req_wrap->dest_len() > 0) {
      argv[0] = UVException(req->result,
                            NULL,
                            req_wrap->syscall(),
                            req_wrap->dest());
    } else {
      argv[0] = UVException(req->result,
                            NULL,
                            req_wrap->syscall(),
                            static_cast<const char*>(req->path));
    }
  } else {
    // error value is empty or null for non-error.
    argv[0] = Null(env->isolate());

    // All have at least two args now.
    argc = 2;

    switch (req->fs_type) {
      // These all have no data to pass.
      case UV_FS_CLOSE:
      case UV_FS_RENAME:
      case UV_FS_UNLINK:
      case UV_FS_RMDIR:
      case UV_FS_MKDIR:
      case UV_FS_FTRUNCATE:
      case UV_FS_FSYNC:
      case UV_FS_FDATASYNC:
      case UV_FS_LINK:
      case UV_FS_SYMLINK:
      case UV_FS_CHMOD:
      case UV_FS_FCHMOD:
      case UV_FS_CHOWN:
      case UV_FS_FCHOWN:
        // These, however, don't.
        argc = 1;
        break;

      case UV_FS_UTIME:
      case UV_FS_FUTIME:
        argc = 0;
        break;

      case UV_FS_OPEN:
        argv[1] = Integer::New(env->isolate(), req->result);
        break;

      case UV_FS_WRITE:
        argv[1] = Integer::New(env->isolate(), req->result);
        break;

      case UV_FS_STAT:
      case UV_FS_LSTAT:
      case UV_FS_FSTAT:
        argv[1] = BuildStatsObject(env,
                                   static_cast<const uv_stat_t*>(req->ptr));
        break;

      case UV_FS_READLINK:
        argv[1] = String::NewFromUtf8(env->isolate(),
                                      static_cast<const char*>(req->ptr));
        break;

      case UV_FS_READ:
        // Buffer interface
        argv[1] = Integer::New(env->isolate(), req->result);
        break;

      case UV_FS_READDIR:
        {
          char *namebuf = static_cast<char*>(req->ptr);
          int nnames = req->result;

          Local<Array> names = Array::New(env->isolate(), nnames);

          for (int i = 0; i < nnames; i++) {
            Local<String> name = String::NewFromUtf8(env->isolate(), namebuf);
            names->Set(i, name);
#ifndef NDEBUG
            namebuf += strlen(namebuf);
            assert(*namebuf == '\0');
            namebuf += 1;
#else
            namebuf += strlen(namebuf) + 1;
#endif
          }

          argv[1] = names;
        }
        break;

      default:
        assert(0 && "Unhandled eio response");
    }
  }

  req_wrap->MakeCallback(env->oncomplete_string(), argc, argv);

  uv_fs_req_cleanup(&req_wrap->req_);
  delete req_wrap;
}

// This struct is only used on sync fs calls.
// For async calls FSReqWrap is used.
struct fs_req_wrap {
  fs_req_wrap() {}
  ~fs_req_wrap() { uv_fs_req_cleanup(&req); }
  // Ensure that copy ctor and assignment operator are not used.
  fs_req_wrap(const fs_req_wrap& req);
  fs_req_wrap& operator=(const fs_req_wrap& req);
  uv_fs_t req;
};


#define ASYNC_DEST_CALL(func, callback, dest_path, ...)                       \
  Environment* env = Environment::GetCurrent(args.GetIsolate());              \
  FSReqWrap* req_wrap;                                                        \
  char* dest_str = (dest_path);                                               \
  int dest_len = dest_str == NULL ? 0 : strlen(dest_str);                     \
  char* storage = new char[sizeof(*req_wrap) + dest_len];                     \
  req_wrap = new(storage) FSReqWrap(env, #func);                              \
  req_wrap->dest_len(dest_len);                                               \
  if (dest_str != NULL) {                                                     \
    memcpy(const_cast<char*>(req_wrap->dest()),                               \
           dest_str,                                                          \
           dest_len + 1);                                                     \
  }                                                                           \
  int err = uv_fs_ ## func(env->event_loop() ,                                \
                           &req_wrap->req_,                                   \
                           __VA_ARGS__,                                       \
                           After);                                            \
  req_wrap->object()->Set(env->oncomplete_string(), callback);                \
  req_wrap->Dispatched();                                                     \
  if (err < 0) {                                                              \
    uv_fs_t* req = &req_wrap->req_;                                           \
    req->result = err;                                                        \
    req->path = NULL;                                                         \
    After(req);                                                               \
  }                                                                           \
  args.GetReturnValue().Set(req_wrap->persistent());

#define ASYNC_CALL(func, callback, ...)                                       \
  ASYNC_DEST_CALL(func, callback, NULL, __VA_ARGS__)                          \

#define SYNC_DEST_CALL(func, path, dest, ...)                                 \
  fs_req_wrap req_wrap;                                                       \
  int err = uv_fs_ ## func(env->event_loop(),                                 \
                         &req_wrap.req,                                       \
                         __VA_ARGS__,                                         \
                         NULL);                                               \
  if (err < 0) {                                                              \
    if (dest != NULL &&                                                       \
        (err == UV_EEXIST ||                                                  \
         err == UV_ENOTEMPTY ||                                               \
         err == UV_EPERM)) {                                                  \
      return env->ThrowUVException(err, #func, "", dest);                     \
    } else {                                                                  \
      return env->ThrowUVException(err, #func, "", path);                     \
    }                                                                         \
  }                                                                           \

#define SYNC_CALL(func, path, ...)                                            \
  SYNC_DEST_CALL(func, path, NULL, __VA_ARGS__)                               \

#define SYNC_REQ req_wrap.req

#define SYNC_RESULT err


static void Close(const FunctionCallbackInfo<Value>& args) {
  Environment* env = Environment::GetCurrent(args.GetIsolate());
  HandleScope scope(env->isolate());

  if (args.Length() < 1 || !args[0]->IsInt32()) {
    return THROW_BAD_ARGS;
  }

  int fd = args[0]->Int32Value();

  if (args[1]->IsFunction()) {
    ASYNC_CALL(close, args[1], fd)
  } else {
    SYNC_CALL(close, 0, fd)
  }
}

你可能感兴趣的:(callback)