forked from tmikov/hermes-jsi-demos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhost-functions.cpp
73 lines (60 loc) · 1.85 KB
/
host-functions.cpp
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
/*
* This is free and unencumbered software released into the public domain.
* For more information, please refer to the LICENSE file in the root directory
* or at <http://unlicense.org/>
*/
#include <fstream>
#include <iostream>
#include <optional>
#include <sstream>
#include <hermes/hermes.h>
#include "natives.h"
/// Read the contents of a file into a string.
static std::optional<std::string> readFile(const char *path) {
std::ifstream fileStream(path);
std::stringstream stringStream;
if (fileStream) {
stringStream << fileStream.rdbuf();
fileStream.close();
} else {
// Handle error - file opening failed
std::cerr << path << ": error opening file" << std::endl;
return std::nullopt;
}
return stringStream.str();
}
int main(int argc, char **argv) {
// If no argument is provided, print usage and exit.
if (argc != 2) {
std::cout << "Usage: " << argv[0] << " <path-to-js-file>" << std::endl;
return 1;
}
const char *jsPath = argv[1];
// Read the file.
auto optCode = readFile(jsPath);
if (!optCode)
return 1;
// You can Customize the runtime config here.
auto runtimeConfig =
hermes::vm::RuntimeConfig::Builder().withIntl(false).build();
// Create the Hermes runtime.
auto runtime = facebook::hermes::makeHermesRuntime(runtimeConfig);
// Register host functions.
registerNatives(*runtime);
// Execute some JS.
int status = 0;
try {
runtime->evaluateJavaScript(
std::make_unique<facebook::jsi::StringBuffer>(std::move(*optCode)),
jsPath);
} catch (facebook::jsi::JSError &e) {
// Handle JS exceptions here.
std::cerr << "JS Exception: " << e.getStack() << std::endl;
status = 1;
} catch (facebook::jsi::JSIException &e) {
// Handle JSI exceptions here.
std::cerr << "JSI Exception: " << e.what() << std::endl;
status = 1;
}
return status;
}