0

What is the easiest way to send variable from nodeJS to C program (NOT C++)? And run this C program after receiving a variable?

app.js :

 var test = 1;

test.c :

#include <stdio.h>     
int main()
{
  int node_variable;
  printf("Value from nodeJS is %d", node_variable);

  return 0;
}
EstevaoLuis
  • 2,422
  • 7
  • 33
  • 40
Timofeev
  • 3
  • 1
  • What you do mean by "send variable"? You can pass values as arguments to C program. – P.P Feb 02 '17 at 13:28
  • 1
    Pass it as a command line argument => [Pass arguments into C program from command line](http://stackoverflow.com/questions/498320/pass-arguments-into-c-program-from-command-line) – Alex K. Feb 02 '17 at 13:28
  • Yes, you're right! I mean pass values to C program.. – Timofeev Feb 02 '17 at 13:30

1 Answers1

1

You can use nodejs child_process module to pass your arguments to your C program (see here for instance).

app.js:

var test = 1;
var exec = require('child_process').exec;
exec('./test.bin '+test, function callback(error, stdout, stderr){console.log(stdout);});

test.c:

#include <stdio.h>

int main(int argc, char **argv) {

  printf("value of test: %s\n", argv[1]);
  return 0;
}

Assuming test.bin is the program built from test.c, executing the javascript file makes the compiled program display the value of test (here, "1"). Be careful the value of the variable test is considered as a single (not empty) argument.

Community
  • 1
  • 1
Emmanuel Lonca
  • 196
  • 1
  • 4
  • Thank you very much for your help! But I have a question: can i display this printf from c in the console? Because now i get empty line.. – Timofeev Feb 02 '17 at 15:18
  • Ok, i got it :D forgot to compile... gcc test.c -o test – Timofeev Feb 02 '17 at 15:42
  • The code from the C program is not directly printed to the standard output ; it is sent to the callback method using the `stdout` parameter. To write it in the console, just call `console.log(stdout);` in the callback method, like in my example. – Emmanuel Lonca Feb 02 '17 at 15:45