Skip to content

Instantly share code, notes, and snippets.

@legraphista
Created November 26, 2018 15:22
Show Gist options
  • Save legraphista/7f098c04e12116ed683ed6cd0b813098 to your computer and use it in GitHub Desktop.
Save legraphista/7f098c04e12116ed683ed6cd0b813098 to your computer and use it in GitHub Desktop.
Minimal Napi Tensorflow C++ example

Requirements

Tensorflow C++ API installed under /usr/local/tensorflow with GPU support

{
"targets": [
{
"target_name": "napi-testing",
'include_dirs': [
"<!@(node -p \"require('node-addon-api').include\")",
"src",
"/usr/local/include",
"/usr/local/tensorflow/include/"
],
'dependencies': ["<!(node -p \"require('node-addon-api').gyp\")"],
"cflags" : [
"-std=c++11",
"-L/usr/local/tensorflow/lib",
"-Wl,-rpath,/usr/local/tensorflow/lib"
],
'cflags!': [ '-fno-exceptions', "-fno-rtti", '-D_THREAD_SAFE' ],
"cflags_cc!": [ "-fno-rtti", "-fno-exceptions" ],
"libraries": [
"<!(node ./libs)"
],
"sources": [
"<!@(ls -1 *.cc)"
],
}
]
}
#include <napi.h>
#include <tensorflow/core/public/session.h>
#include <tensorflow/core/protobuf/meta_graph.pb.h>
using namespace tensorflow;
using namespace Napi;
using namespace std;
Object Init(Napi::Env env, Object exports) {
Napi::HandleScope scope(env);
auto opts = SessionOptions();
auto session = NewSession(opts);
return exports;
}
NODE_API_MODULE(testing, Init);
const libPaths = [
'/usr/local/tensorflow/lib',
'/usr/local/lib'
];
const tfLibList = [
"tensorflow_cc",
"tensorflow_framework"
].map(x => `-l${x}`);
const paths = [];
libPaths.forEach(libPath => {
paths.push(`-L${libPath}`);
paths.push(`-Wl,-rpath,${libPath}`);
});
paths.push(...tfLibList);
console.log(paths.join(' '));
{
"name": "napi-testing",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "node-gyp build",
"install": "node-gyp rebuild",
"start": "node ./index.js",
"debug": "node-gyp build --debug -j1 CXXFLAGS=\"-Wno-deprecated -Wno-deprecated-declarations\"",
"configure": "node-gyp configure",
"configure:xcode": "node-gyp configure -- -f xcode",
"configure:cmake": "node-gyp configure -- -f cmake",
"cfg": "npm run configure && npm run configure:xcode && npm run configure:cmake",
"clean": "node-gyp clean"
},
"author": "Stefan-Gabriel Muscalu <stefan.gabriel.muscalu@gmail.com> (http://my.corneroftheinternet.rocks/)",
"license": "MIT",
"dependencies": {
"bindings": "^1.3.0",
"node-addon-api": "^1.6.1"
}
}
const testing = require('bindings')('napi-testing');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment