Call a foreign-language function: Difference between revisions

Added JavaScript solution using Node.js and node-api
(Added Zig)
(Added JavaScript solution using Node.js and node-api)
Line 1,072:
</pre>
 
=={{header|JavaScript}}==
'''Node.js'''
 
Node.js provides the node-api tool to help you create native C or C++ addons.
This example will implement openssl's MD5 function in C++, and create Node.js bindings for it.
 
'''md5sum.cc'''
<lang cpp>#include <napi.h>
#include <openssl/md5.h>
 
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
using namespace Napi;
 
Napi::Value md5sum(const Napi::CallbackInfo& info) {
std::string input = info[0].ToString();
 
unsigned char result[MD5_DIGEST_LENGTH];
MD5((unsigned char*)input.c_str(), input.size(), result);
 
std::stringstream md5string;
md5string << std::hex << std::setfill('0');
for (const auto& byte : result) md5string << std::setw(2) << (int)byte;
return String::New(info.Env(), md5string.str().c_str());
}
 
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "md5sum"),
Napi::Function::New(env, md5sum));
return exports;
}
 
NODE_API_MODULE(addon, Init)</lang>
Then compile the file with [https://github.com/nodejs/node-gyp node-gyp].
<lang bash>node-gyp build</lang>
Once it has compiled, create the JavaScript bindings.
 
'''binding.js'''
<lang javascript>const addon = require('../build/Release/md5sum-native');
 
module.exports = addon.md5sum;</lang>
Then, you're able to call the function from any Node.js JavaScript file.
 
''Using Require:''
<lang javascript>const md5sum = require('../lib/binding.js');
console.log(md5sum('hello'));</lang>
{{out}}
<pre>
5d41402abc4b2a76b9719d911017c592
</pre>
''Using Import:''
 
If you wish to use the ESM import syntax, you need to modify your ''binding.js'' file.
 
'''binding.js'''
<lang javascript>import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const addon = require('../build/Release/md5sum-native');
 
export default addon.md5sum;</lang>
And call the function as follows:
<lang javascript>import md5sum from '../lib/binding.js';
 
console.log(md5sum('hello'));</lang>
{{out}}
<pre>
5d41402abc4b2a76b9719d911017c592
</pre>
Learn more on the Node.js [https://nodejs.org/api/addons.html docs].
=={{header|Julia}}==
{{works with|Julia|0.6}}