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;
}
3
  • What you do mean by "send variable"? You can pass values as arguments to C program. Commented Feb 2, 2017 at 13:28
  • 1
    Pass it as a command line argument => Pass arguments into C program from command line Commented Feb 2, 2017 at 13:28
  • Yes, you're right! I mean pass values to C program.. Commented Feb 2, 2017 at 13:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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..
Ok, i got it :D forgot to compile... gcc test.c -o test
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.