-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path15244133646661.html
505 lines (299 loc) · 19.8 KB
/
15244133646661.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>
Native Extension for Node.js - Junkman
</title>
<link href="atom.xml" rel="alternate" title="Junkman" type="application/atom+xml">
<link rel="stylesheet" href="asset/css/foundation.min.css" />
<link rel="stylesheet" href="asset/css/docs.css" />
<script src="asset/js/vendor/modernizr.js"></script>
<script src="asset/js/vendor/jquery.js"></script>
<script src="asset/highlightjs/highlight.pack.js"></script>
<link href="asset/highlightjs/styles/github.css" media="screen, projection" rel="stylesheet" type="text/css">
<script>hljs.initHighlightingOnLoad();</script>
<script type="text/javascript">
function before_search(){
var searchVal = 'site:panlw.github.io ' + document.getElementById('search_input').value;
document.getElementById('search_q').value = searchVal;
return true;
}
</script>
</head>
<body class="antialiased hide-extras">
<div class="marketing off-canvas-wrap" data-offcanvas>
<div class="inner-wrap">
<nav class="top-bar docs-bar hide-for-small" data-topbar>
<section class="top-bar-section">
<div class="row">
<div style="position: relative;width:100%;"><div style="position: absolute; width:100%;">
<ul id="main-menu" class="left">
<li id=""><a target="self" href="index.html">Home</a></li>
<li id=""><a target="_self" href="archives.html">Archives</a></li>
</ul>
<ul class="right" id="search-wrap">
<li>
<form target="_blank" onsubmit="return before_search();" action="http://google.com/search" method="get">
<input type="hidden" id="search_q" name="q" value="" />
<input tabindex="1" type="search" id="search_input" placeholder="Search"/>
</form>
</li>
</ul>
</div></div>
</div>
</section>
</nav>
<nav class="tab-bar show-for-small">
<a href="javascript:void(0)" class="left-off-canvas-toggle menu-icon">
<span> Junkman</span>
</a>
</nav>
<aside class="left-off-canvas-menu">
<ul class="off-canvas-list">
<li><a href="index.html">HOME</a></li>
<li><a href="archives.html">Archives</a></li>
<li><a href="about.html">ABOUT</a></li>
<li><label>Categories</label></li>
<li><a href="Infra.html">Infra</a></li>
<li><a href="Coding.html">Coding</a></li>
<li><a href="Modeling.html">Modeling</a></li>
<li><a href="Archtecting.html">Archtecting</a></li>
</ul>
</aside>
<a class="exit-off-canvas" href="#"></a>
<section id="main-content" role="main" class="scroll-container">
<script type="text/javascript">
$(function(){
$('#menu_item_index').addClass('is_active');
});
</script>
<div class="row">
<div class="large-8 medium-8 columns">
<div class="markdown-body article-wrap">
<div class="article">
<h1>Native Extension for Node.js</h1>
<div class="read-more clearfix">
<span class="date">2018/4/23</span>
<span>posted in </span>
<span class="posted-in"><a href='Node.js.html'>Node.js</a></span>
<span class="comments">
</span>
</div>
</div><!-- article -->
<div class="article-content">
<blockquote>
<p><a href="https://www.nan-labs.com/blog/native-extensions-for-nodejs/">https://www.nan-labs.com/blog/native-extensions-for-nodejs/</a></p>
<p><u>If you are a Spanish reader you can read this post in Spanish here: <a href="http://laplatajs.github.io/blog/2018/02/27/extensiones-nativas.html">Extensiones Nativas: ¿dónde empezar?</a></u></p>
<p>In this article we will talk about the most important concepts to develop native extensions for NodeJS. Later, I will show how to build our first native extension with a practical example. And finally, I will leave some links to read more about it.</p>
</blockquote>
<h2 id="toc_0">The basics to get started with native extensions</h2>
<p>In simple terms, we can say that a native extension is a set of C++ implemented logic that can be invoked from JavaScript code.</p>
<p>At this point, it’s interesting for us to clarify how NodeJS works and which are the parts involved in it. It’s important to know why we can talk about two languages (JavaScript & C++) under the NodeJS context.</p>
<p>I like to explain it this way:</p>
<ul>
<li> <strong>JavaScript</strong>: it’s the coding language.</li>
<li> <strong>V8</strong>: it’s the engine that runs our JavaScript code.</li>
<li> <strong>Libuv</strong>: it’s a C library that provides us with asynchronous execution.</li>
</ul>
<p>Now, where can we place native extensions? I will choose write/read disk action as an example to explain it. Neither JavaScript nor V8 provides us with disk access. Libuv provides asynchronous execution. But, with NodeJS we can write/read to disk, right? Well, this is the point where native extensions get into the match. The fs module is implemented using C++ (it has disk access) and eventually exposes methods (like writeFile and readFile) which can be invoked from JavaScript.</p>
<p><img src="media/15244133646661/15244134699236.jpg" alt="Interaction with native extensions diagram"/></p>
<p>Once we have learned this, we can start taking our first steps in native extensions. Let’s talk about the tools we need.</p>
<h2 id="toc_1">Basic tooling to build a native extension</h2>
<h3 id="toc_2">Binding.gyp file</h3>
<p>This file allows us to specify how we need to compile our native extension. One of the main thing that we need to define are the files that will be compiled and how we will call the final binary. It has a JSON like structure, and the keys to get this configured are sources and target.</p>
<h3 id="toc_3"><a href="https://github.com/nodejs/node-gyp">Node-gyp</a></h3>
<p>It’s the tool that allows us to compile our native extension. It’s implemented in NodeJS and it’s bundled with npm so we can just run npm install and that will compile our native extension. When we run npm install, it will detect our binding.gyp file included in our root folder and then it will start compiling.</p>
<p>Also, it allows us to make release(default) or debug builds. As a result, a binary file with .node extension will be created inside a release or debug folder, depending on how it was configured.</p>
<h3 id="toc_4"><a href="https://github.com/TooTallNate/node-bindings">Bindings</a></h3>
<p>It’s a NodeJS package which allows us to export our native extension. It’s in charge of searching in a build or release folder for us.</p>
<h3 id="toc_5"><a href="https://nodejs.org/api/n-api.html">N-API</a></h3>
<p>It’s C API that allows us to interact with our engine in a completely abstract way. For me, it’s the result of an evolution that tries to port node to different architectures.</p>
<p>N-API provides stability and compatibility between different node versions. That is, if my native extension is compiled to node 8.1, I don’t need to compile it again for node 8.6 or 9.3. Thus making the life of the maintainers and contributors easier.</p>
<p>At this moment, N-API is under <a href="https://nodejs.org/docs/latest/api/n-api.html#n_api_n_api">experimental state</a>.</p>
<h3 id="toc_6"><a href="https://github.com/nodejs/node-addon-api">Node addon api</a></h3>
<p>This NodeJS module provides us with a C++ implementation of N-API and allows us to use the language advantages.</p>
<h2 id="toc_7">First steps in the native extension world</h2>
<p><u>Note: For this example, I used node 9.3.</u></p>
<p>To get initiated on the native extension world we will use the classic hello world example. The idea is to not overload the code with extra logic so we can focus on the minimum necessary code.</p>
<p>We start initializing npm so that we can then install our dependencies:</p>
<p><code>npm init</code></p>
<p>Now, as we said, we install our dependencies:</p>
<p><code>npm i node-addon-api bindings</code></p>
<p>At this point we need to create our C file with our logic:</p>
<p><link rel="stylesheet" href="https://assets-cdn.github.com/assets/gist-embed-1baaff35daab552f019ad459494450f1.css"></p>
<pre><code class="language-cpp">#include <napi.h>
Napi::String SayHi(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
return Napi::String::New(env, "Hi!");
}
Napi::Object init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "sayHi"), Napi::Function::New(env, SayHi));
return exports;
};
NODE_API_MODULE(hello_world, init);
</code></pre>
<blockquote>
<p><a href="https://gist.github.com/nanlabsweb/d6c985ee9842fab274d4116c2fb0f443/raw/188b287e5092727700cfe1ddff8f6cbc402f3e3e/hello_world.cc">view raw</a> <a href="https://gist.github.com/nanlabsweb/d6c985ee9842fab274d4116c2fb0f443#file-hello_world-cc">hello_world.cc</a> hosted with ❤ by <a href="https://github.com">GitHub</a></p>
</blockquote>
<p>This file has three important parts that will be explained from bottom to top:</p>
<ul>
<li> <strong>NODE_API_MODULE</strong> (Line 14): The first argument is the native extension name and the second one is the name of the function that initializes our extension.</li>
<li> <strong>Init</strong> (Line 10): This is the function that will initialize our native extension. In this function we must export the functions that will be invoked from JavaScript code. To do this, we need to set the name of the function to the exports object and the function itself that will be invoked. This init function must return the exports object.</li>
<li> <strong>SayHi</strong> (Line 3): This function is what will be executed when we invoke our native extension from our JavaScript.</li>
</ul>
<p>Later, we need to create our <strong>binding.gyp</strong> file that will contain our native extension configuration:</p>
<p><link rel="stylesheet" href="https://assets-cdn.github.com/assets/gist-embed-1baaff35daab552f019ad459494450f1.css"></p>
<pre><code class="language-json">{
"targets": [
{
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
"include_dirs" : [
"<!@(node -p \"require('node-addon-api').include\")"
],
"target_name": "hello_world",
"sources": [ "hello_world.cc" ],
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ]
}
]
}
</code></pre>
<blockquote>
<p><a href="https://gist.github.com/nanlabsweb/ebbc7d0c2dd5249b5f833e8a2b845f5d/raw/61068384831764b78bc8a7ace9deedefb1faadc5/binding.gyp">view raw</a> <a href="https://gist.github.com/nanlabsweb/ebbc7d0c2dd5249b5f833e8a2b845f5d#file-binding-gyp">binding.gyp</a> hosted with ❤ by <a href="https://github.com">GitHub</a></p>
</blockquote>
<p>Finally, the JavaScript code that will require our extension and invoke it.</p>
<p><link rel="stylesheet" href="https://assets-cdn.github.com/assets/gist-embed-1baaff35daab552f019ad459494450f1.css"></p>
<pre><code>const hello_world = require('bindings')('hello_world')
console.log(hello_world.sayHi());
</code></pre>
<blockquote>
<p><a href="https://gist.github.com/nanlabsweb/30019fc7ae72f3898f93623d535d8790/raw/a43850af02bfb800bad0ab82426c64b307f50e1c/index.js">view raw</a> <a href="https://gist.github.com/nanlabsweb/30019fc7ae72f3898f93623d535d8790#file-index-js">index.js</a> hosted with ❤ by <a href="https://github.com">GitHub</a></p>
</blockquote>
<p>Now, we just need to compile our extension running npm install and run the JavaScript file that is used:</p>
<p><img src="media/15244133646661/15244136958142.gif" alt="Native extensions gif demonstrating real usage."/></p>
<p>And that’s it. We just run our native extension.</p>
<h2 id="toc_8">What we had before N-API?</h2>
<p>I find it important to know the context and history of native extensions since it gives access to a lot of documentation and examples. The idea is for N-API to eventually replace NAN. For that reason we should look back to NAN for a moment.</p>
<p>NAN? Yes, <a href="https://github.com/nodejs/nan">Native Abstraction for Node.js</a>. NAN is a C++ library that provides us with V8 abstraction, but it doesn’t allow us to abstract ourselves from the V8.<br/>
In new NodeJS releases, there could be V8 changes that could break our native extension. Using NAN is a way to avoid this problem.</p>
<h2 id="toc_9">Further steps to develop your native extensions</h2>
<p>As I said, knowing about NAN allows us to learn from its examples and documentation. It’s a good complement to our native extension learning process.</p>
<ul>
<li> NAPI examples can be found in <a href="https://github.com/nodejs/node/tree/master/test/addons-napi">here</a>.</li>
<li> Node-addon-api examples can be found in <a href="https://github.com/nodejs/abi-stable-node-addon-examples">here</a>.</li>
<li> Nan examples can be found in <a href="https://github.com/nodejs/nan/tree/master/test">here</a>.</li>
<li> Another good source are tests <a href="https://github.com/nodejs/node-addon-api/tree/master/test">here</a>.</li>
<li> To learn more about native extensions <a href="https://nodeaddons.com/">here</a>.</li>
</ul>
<h2 id="toc_10">Conclusion</h2>
<p>Learning about native extensions helped me to understand how NodeJS works and how it’s composed. There are more than one scenario where we can use them, such as performance boosts, C/C++ library integrations, or integration with legacy code.</p>
<p>In summary, it’s an excellent way to learn about NodeJS internals.</p>
<p>If you have any doubt, please post a comment and I will help you.</p>
<h3 id="toc_11">Taking part in the community</h3>
<p>I made this post for a contribution to <a href="http://laplatajs.github.io/">LaPlataJS</a>. It’s a local JavaScript community where I participate helping with talks, events organization, or posts. I think that whenever you can you should join a community. For me, it has a lot of benefits. You can know really good people, share ideas, learn things and, sometimes, go for a beer with your folks.</p>
</div>
<div class="row">
<div class="large-6 columns">
<p class="text-left" style="padding:15px 0px;">
<a href="15246678052226.html"
title="Previous Post: 阿里云Redis开发规范">« 阿里云Redis开发规范</a>
</p>
</div>
<div class="large-6 columns">
<p class="text-right" style="padding:15px 0px;">
<a href="15244093031262.html"
title="Next Post: A GraphQL & Node.js Express Tutorial: Powerful E-Commerce with GraphCMS">A GraphQL & Node.js Express Tutorial: Powerful E-Commerce with GraphCMS »</a>
</p>
</div>
</div>
<div class="comments-wrap">
<div class="share-comments">
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5ae58078c0d7b2ab"></script>
</div>
</div>
</div><!-- article-wrap -->
</div><!-- large 8 -->
<div class="large-4 medium-4 columns">
<div class="hide-for-small">
<div id="sidebar" class="sidebar">
<div id="site-info" class="site-info">
<div class="site-a-logo"><img src="./asset/img/logo.jpg" /></div>
<h1>Junkman</h1>
<div class="site-des">“拾荒者”一词来自凯文・凯利的《失控》中关于机器学习的故事(“收集癖好机”如何完成他的收集工作)。</div>
<div class="social">
<a target="_blank" class="github" target="_blank" href="https://github.com/panlw/" title="GitHub">GitHub</a>
<a target="_blank" class="rss" href="atom.xml" title="RSS">RSS</a>
</div>
</div>
<div id="site-categories" class="side-item ">
<div class="side-header">
<h2>Categories</h2>
</div>
<div class="side-content">
<p class="cat-list">
<a href="Infra.html"><strong>Infra</strong></a>
<a href="Coding.html"><strong>Coding</strong></a>
<a href="Modeling.html"><strong>Modeling</strong></a>
<a href="Archtecting.html"><strong>Archtecting</strong></a>
</p>
</div>
</div>
<div id="site-categories" class="side-item">
<div class="side-header">
<h2>Recent Posts</h2>
</div>
<div class="side-content">
<ul class="posts-list">
<li class="post">
<a href="15517999043443.html">The Art of Crafting Architectural Diagrams</a>
</li>
<li class="post">
<a href="15517997955971.html">为什么说我们需要软件架构图?</a>
</li>
<li class="post">
<a href="15516128677869.html">DNS Servers That Offer Privacy and Filtering</a>
</li>
<li class="post">
<a href="15516123108194.html">Airbnb's Migration from Monolith to Services</a>
</li>
<li class="post">
<a href="15516097487470.html">Events As First-Class Citizens</a>
</li>
</ul>
</div>
</div>
</div><!-- sidebar -->
</div><!-- hide for small -->
</div><!-- large 4 -->
</div><!-- row -->
<div class="page-bottom clearfix">
<div class="row">
<p class="copyright">Copyright © 2015
Powered by <a target="_blank" href="http://www.mweb.im">MWeb</a>,
Theme used <a target="_blank" href="http://github.com">GitHub CSS</a>.</p>
</div>
</div>
</section>
</div>
</div>
<script src="asset/js/foundation.min.js"></script>
<script>
$(document).foundation();
function fixSidebarHeight(){
var w1 = $('.markdown-body').height();
var w2 = $('#sidebar').height();
if (w1 > w2) { $('#sidebar').height(w1); };
}
$(function(){
fixSidebarHeight();
})
$(window).load(function(){
fixSidebarHeight();
});
</script>
<script src="asset/chart/all-min.js"></script><script type="text/javascript">$(function(){ var mwebii=0; var mwebChartEleId = 'mweb-chart-ele-'; $('pre>code').each(function(){ mwebii++; var eleiid = mwebChartEleId+mwebii; if($(this).hasClass('language-sequence')){ var ele = $(this).addClass('nohighlight').parent(); $('<div id="'+eleiid+'"></div>').insertAfter(ele); ele.hide(); var diagram = Diagram.parse($(this).text()); diagram.drawSVG(eleiid,{theme: 'simple'}); }else if($(this).hasClass('language-flow')){ var ele = $(this).addClass('nohighlight').parent(); $('<div id="'+eleiid+'"></div>').insertAfter(ele); ele.hide(); var diagram = flowchart.parse($(this).text()); diagram.drawSVG(eleiid); } });});</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script><script type="text/x-mathjax-config">MathJax.Hub.Config({TeX: { equationNumbers: { autoNumber: "AMS" } }});</script>
</body>
</html>