设为首页 收藏本站
查看: 851|回复: 0

[经验分享] nodejs callback

[复制链接]

尚未签到

发表于 2017-2-21 08:02:30 | 显示全部楼层 |阅读模式
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)
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-344943-1-1.html 上篇帖子: windows下nodejs环境配置 下篇帖子: NodeJs 的安装
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表