Ask Your Question
4

How do you use process.argv in a C++ addon for Node.js?

asked 2022-02-21 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-11-02 10:00:00 +0000

bukephalos gravatar image

Process.argv is a Node.js builtin that provides an array of command-line arguments that were passed when starting the Node.js process. In order to use process.argv in a C++ addon for Node.js, you can include the headers <node.h> and <v8.h> and define a function that accepts arguments from the process.argv array.

Here is an example of a C++ addon that uses process.argv to print the command-line arguments:

#include <node.h>
#include <v8.h>

using namespace v8;

void PrintArgs(const FunctionCallbackInfo<Value>& args)
{
    Isolate* isolate = args.GetIsolate();
    Local<Array> argv = Array::New(isolate, args.Length());

    for(int i = 0; i < args.Length(); i++)
    {
        argv->Set(i, args[i]);
    }

    String::Utf8Value cmdLine(argc ? argv[i] : "");
    printf("Command line: %s\n", *cmdLine);
}

void Init(Local<Object> exports)
{
    NODE_SET_METHOD(exports, "printArgs", PrintArgs);
}

NODE_MODULE(addon, Init)

In this example, we first define a function called PrintArgs that accepts a FunctionCallbackInfo object as its argument. This object contains information about the current execution context, including the array of arguments that were passed to the Node.js process.

We then create a new array object in V8 using the Array::New() method, and fill it with the arguments in the process.argv array. We then use a for loop to iterate through this new array and print each argument to the console using printf.

Finally, we define an Init() function that registers the PrintArgs function as a method of the exports object, and call the NODE_MODULE macro to create the Node.js addon module. This allows us to use our C++ addon from Node.js, and call the printArgs() method to print the command-line arguments.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-21 11:00:00 +0000

Seen: 12 times

Last updated: Nov 02 '21