1
1
#define NAPI_VERSION 3
2
2
3
+ #include < string.h>
3
4
#include < node_api.h>
4
5
#include < napi-macros.h>
5
6
@@ -58,7 +59,6 @@ napi_value addOne (napi_env env, napi_callback_info info) {
58
59
return return_int32;
59
60
}
60
61
61
-
62
62
/* *
63
63
* Using n-api macros instead removes alot of boilerplate
64
64
* This function is basically the same as `addOne`
@@ -90,7 +90,7 @@ NAPI_METHOD(createArr) {
90
90
NAPI_METHOD (createObj) {
91
91
napi_value obj;
92
92
NAPI_STATUS_THROWS (napi_create_object (env, &obj))
93
- // we need to set a string
93
+ // Set a value on the obj
94
94
napi_value value;
95
95
NAPI_STATUS_THROWS (napi_create_string_utf8 (
96
96
env,
@@ -104,9 +104,44 @@ NAPI_METHOD(createObj) {
104
104
105
105
/* *
106
106
* Takes an object and sets a property on it
107
+ * Object must be { key1: "some string" }
108
+ * Will return object new property key2
107
109
*/
108
- // NAPI_METHOD(setProperty) {
109
- // }
110
+ NAPI_METHOD (setProperty) {
111
+ NAPI_ARGV (1 )
112
+ // Expect an object argument
113
+ napi_value obj = argv[0 ];
114
+ // Extract property key1, and expect it to be a string
115
+ napi_value keyValue;
116
+ NAPI_STATUS_THROWS (napi_get_named_property (env, obj, " key1" , &keyValue))
117
+ // Find the JS length of the string
118
+ size_t keyValueLength;
119
+ NAPI_STATUS_THROWS (napi_get_value_string_utf8 (
120
+ env,
121
+ keyValue,
122
+ NULL ,
123
+ 0 ,
124
+ &keyValueLength
125
+ ))
126
+ // Convert the value to a C string
127
+ NAPI_UTF8 (keyValueString, keyValueLength + 1 , keyValue)
128
+ keyValueString[keyValueLength + 1 ] = ' \0 ' ;
129
+ // Concatenate the string
130
+ char fullString[8 + keyValueLength + 1 ] = {0 };
131
+ strcat (fullString, " initial " );
132
+ strcat (fullString, keyValueString);
133
+ // Convert the C string back to JS string
134
+ napi_value fullStringJS;
135
+ NAPI_STATUS_THROWS (napi_create_string_utf8 (
136
+ env,
137
+ fullString,
138
+ NAPI_AUTO_LENGTH,
139
+ &fullStringJS
140
+ ))
141
+ // Set the the new string as new of property key2
142
+ NAPI_STATUS_THROWS (napi_set_named_property (env, obj, " key2" , fullStringJS));
143
+ return obj;
144
+ }
110
145
111
146
/* *
112
147
* All exported functions
@@ -138,4 +173,5 @@ NAPI_INIT() {
138
173
NAPI_EXPORT_FUNCTION (timesTwo)
139
174
NAPI_EXPORT_FUNCTION (createArr)
140
175
NAPI_EXPORT_FUNCTION (createObj)
176
+ NAPI_EXPORT_FUNCTION (setProperty)
141
177
}
0 commit comments