本文详细介绍了如何从零基础开发一个跨平台的 node.js addons 插件,实现一个 sleep 函数。通过前两节的学习,我们已经掌握了如何编写简单的 node.js addons 插件,包括参数接收和类型转换等内容。然而,之前的插件编译仅考虑了一个平台,而实际应用中可能需要跨平台支持。因此,本文将展示如何通过 c/c++ 实现一个跨平台的 sleep 函数,并在 node.js 中使用。

项目结构
项目结构如下:
├── binding.gyp ├── index.d.ts ├── index.js ├── package.json ├── src │ ├── sleep.h │ ├── sleep_init.c │ ├── sleep_linux.c │ └── sleep_win.c
核心编码实现
sleep_init.c
这是我们初始化的入口文件,主要用于模块的注册和导出我们定义的方法。注意 #include "sleep.h" 这个宏定义是我们自己实现的,代码中 os_usleep() 函数是在这个文件中定义的。
#include "sleep.h"
#include <node_api.h>
<p>napi_value usleepFn(napi_env env, napi_callback_info info) {
size_t argc = 1;
napi_value argv[1];
NAPI_STATUS_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL));
if (argc < 1) {
napi_throw_error(env, NULL, "usleep requires one argument");
return NULL;
}</p><p>double microseconds;
NAPI_STATUS_CALL(env, napi_get_value_double(env, argv[0], µseconds));</p><p>int result = os_usleep((unsigned int)microseconds);
napi_value resultValue;
NAPI_STATUS_CALL(env, napi_create_int32(env, result, &resultValue));</p><p>return resultValue;
}</p><p>napi_value Init(napi_env env, napi_value exports) {
napi_value fn;
NAPI_STATUS_CALL(env, napi_create_function(env, NULL, 0, usleepFn, NULL, &fn));
NAPI_STATUS_CALL(env, napi_set_named_property(env, exports, "usleep", fn));
return exports;
}</p><p>NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)sleep.h
在这个头文件中,我们声明了 os_usleep() 函数。通常在 C/C++ 程序中,建议将所有的常量、宏、函数原型写在头文件中,实现则在引入该头文件的地方。
#include <node_api.h></p><h1>define NAPI_STATUS_CALL(env, call) \</h1><p>do { \
napi_status status = (call); \
if (status != napi_ok) { \
const napi_extended_error_info<em> error_info = NULL; \
napi_get_last_error_info((env), &error_info); \
bool is_pending; \
napi_is_exception_pending((env), &is_pending); \
if (!is_pending) { \
const char</em> error_message = error_info->error_message != NULL \
? error_info->error_message \
: "empty error message"; \
napi_throw_error((env), NULL, error_message); \
return NULL; \
} \
} \
} while(0)</p><p>int os_usleep(unsigned int microseconds);sleep_linux.c
在 Linux 系统下,睡眠函数的实现使用 usleep() 函数,单位是微秒,需要引入 unistd.h 头文件。
#include "sleep.h"</p><h1>include <unistd.h></h1><p>int os_usleep(unsigned int microseconds) {
// Return 0 on success, return -1 on error
int usleepRes = usleep(microseconds);
return usleepRes;
}sleep_win.c
在 Windows 系统下,需要引入 windows.h 头文件,注意首字母为大写,单位为毫秒。
#include "sleep.h"</p><h1>include <windows.h></h1><p>/** </p><ul><li>The unit of Windows system Sleep() is microseconds
<em>/
int os_usleep(unsigned int microseconds) {
unsigned int miliseconds = microseconds / 1000;
Sleep(miliseconds);
return 0;
}构建
创建 binding.gyp 文件,sources 加载所有 C 源码,具体编译哪些文件,还需通过 conditions 判断,根据不同的系统从 sources 中排除。
{
"targets": [
{
"target_name": "easy-sleep",
"sources": [
"src/sleep_init.c",
"src/sleep.h",
"src/sleep_win.c",
"src/sleep_linux.c"
],
"conditions": [
[
'OS == "win"', {
"sources!": ["src/sleep_linux.c"]
},
'OS != "win"', {
"sources!": ["src/sleep_win.c"]
}
]
]
}
]
}编译
在项目根目录执行如下命令进行编译:
node-gyp configure build
测试
和第一讲的方式一样,创建 app.js 文件,引入我们编译之后的 .node 文件。因为我们在 C 里面实现时单位是微秒,所以需要在转换下。
const { usleep } = require('./build/Release/easy-sleep.node');
console.log(1)
usleep(2000 </em> 1000); // 等待 2 秒
console.log(2)总结
上述还有一个不完美的地方就是构建 C 源码部分,通常必须要求用户本地也有一个能够编译 C/C++ 代码的环境,例如我们使用 node-gyp 工具在 Linux 系统要安装 Python、GCC,Windows 系统同样也要安装相应的构建环境,对于用户来说是一个极大的障碍,总不能要求用户同样也安装这些工具。
如果我们想实现跨平台支持,又无需用户在本地安装 C/C++ 工具链该怎么做?可以自己先思考下,也可以关注下节内容,node-pre-gyp 结合 Github Actions 预先构建二进制包。
- END -










