简体   繁体   中英

C++ node.js module. cout not working?

Hi I am a noob in C++ trying to modify an existing native node module.

I am trying to add couts inside the module to print info I think is useful for me.

NAN_METHOD(Context2d::SetFillRule){
  Context2d *context = Nan::ObjectWrap::Unwrap<Context2d>(info.This());
  cairo_t *ctx = context->context();
  String::Utf8Value str(info[0]);
  cout << "set method called";
  ...
}

The previous method is working but the cout is never shown. Is it lost/shown during the node-gyp build? Have I done something wrong? is there a way to accomplish it?

I am trying to learn N-API to make an addon for a nodejs project and just had the same issue. Adding #include <iostream> made std::cout available for use in my code. When I run my code by calling node path_to_file.js as I would for any nodejs project, it successfully prints my data to the console. I know that you are using NAN and probably already overcame this issue a long time ago, but I felt it was important to give this answer since this showed up in my search results and there was not a good answer for beginners like me.

I'd suggest writing it to a log file instead (redirecting std::cout is a pain).

std::ofstream logFile("logfile.txt");
logFile << "set method called";

std::cout << in a Node.js C++ add-on is supposed to normally print to the console (the stdout of the node process).

If it doesn't appear, it's likely segmentation faults due to poor memory (instance lifespan) management. It kills the entire node process silently .

The cout << "some text" will only works if you launch your binary straight from the command line. I think it is not the case, as appears you are using it inside node. So you should find some log output method from node libraries.

If it is in windows you can try to make another console window.Then bind your contex to that window and redirect the print to there.

or write into a file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM