mirror of
https://github.com/jerryscript-project/jerryscript.git
synced 2025-12-15 16:29:21 +00:00
2.9 KiB
2.9 KiB
| layout | title | permalink |
|---|---|---|
| page | Development | /dev-guide/ |
Embedding
The JerryScript Engine can be embedded into any application, providing way to run JavaScript in large range of environments - from desktops to low-memory microcontrollers.
How to execute simple JavaScript file from your application
#include <string.h>
#include "jerry.h"
int
main (int argc, char * argv[]) {
char script [] = "print ('Hello, World!');";
jerry_init (JERRY_FLAG_EMPTY);
jerry_parse (script, strlen (script));
jerry_run ();
jerry_cleanup ();
}
The described application will generate the following output:
Hello, World!
Simple JavaScript shell
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "jerry.h"
static void
print_value (const jerry_api_value_t * value_p);
int
main (int argc, char * argv[]) {
jerry_init (JERRY_FLAG_EMPTY);
char cmd [256];
while (true) {
printf ("> ");
if (fgets (cmd, sizeof (cmd), stdin) == NULL
|| strcmp (cmd, "quit\n") == 0) {
break;
}
jerry_api_value_t ret_val;
jerry_completion_code_t status = jerry_api_eval (cmd, strlen (cmd),
false, false,
&ret_val);
if (status == JERRY_COMPLETION_CODE_OK) {
// 'eval' completed successfully
print_value (&ret_val);
jerry_api_release_value (&ret_val);
} else {
// evaluated JS code thrown an exception
// and didn't handle it with try-catch-finally
printf ("Unhandled JS exception occured\n");
}
printf ("\n");
fflush (stdout);
}
jerry_cleanup ();
return 0;
}
static void
print_value (const jerry_api_value_t * value_p)
{
switch (value_p->type)
{
case JERRY_API_DATA_TYPE_UNDEFINED:
printf ("undefined");
break;
case JERRY_API_DATA_TYPE_NULL:
printf ("null");
break;
case JERRY_API_DATA_TYPE_BOOLEAN:
if (value_p->v_bool)
printf ("true");
else
printf ("false");
break;
case JERRY_API_DATA_TYPE_FLOAT64:
printf ("%lf", value_p->v_float64);
break;
case JERRY_API_DATA_TYPE_STRING:
{
ssize_t neg_req_sz, sz;
// determining required buffer size
neg_req_sz = jerry_api_string_to_char_buffer (value_p->v_string,
NULL,
0);
assert (neg_req_sz < 0);
char * str_buf_p = (char*) malloc (-neg_req_sz);
sz = jerry_api_string_to_char_buffer (value_p->v_string,
str_buf_p,
-neg_req_sz);
assert (sz == -neg_req_sz);
printf ("%s", str_buf_p);
free (str_buf_p);
break;
}
case JERRY_API_DATA_TYPE_OBJECT:
printf ("[JS object]");
break;
}
printf ("\n");
}