2

I have c++ code wrapped using node-addon-api:

Napi::String Method(const Napi::CallbackInfo &info)
{
  Napi::Env env = info.Env();
  time_t rawtime;
  struct tm *timeinfo;
  char system_date_buffer[80];
  char iso_date_buffer[80];

  time(&rawtime);
  timeinfo = localtime(&rawtime);

  setlocale(LC_ALL, "");
  strftime(system_date_buffer, 80, "%x", timeinfo);
  string sysDateFormat(system_date_buffer);
  strftime(iso_date_buffer, 80, "%%Y-%m-%d", timeinfo);
  string isoDateFormat(iso_date_buffer);
  return Napi::String::New(env, sysDateFormat);
}

Init:

Napi::Object Init(Napi::Env env, Napi::Object exports)
{
  exports.Set(Napi::String::New(env, "sysDateFormat"), Napi::Function::New(env, Method));
  exports.Set(Napi::String::New(env, "isoDateFormat"), Napi::Function::New(env, Method));
  return exports;
}

How do I return different values or export an object? Above I am returning only

return Napi::String::New(env, sysDateFormat);

How do I return isoDateFormat also? My idea is to put sysDateFormat and isoDateFormat in to object and return it but not sure of syntax

Currently I am returning only string

Update:

I have used array to store both values but return type is showing compile time error: no instance of overloaded function "Napi::Array::New" matches the argument list -- argument types are: (Napi::Env, std::string [2])

Napi::Array Method(const Napi::CallbackInfo &info)
{
  Napi::Env env = info.Env();
  time_t rawtime;
  struct tm *timeinfo;
  char system_date_buffer[80];
  char iso_date_buffer[80];
  string dateArray [2];

  time(&rawtime);
  timeinfo = localtime(&rawtime);

  setlocale(LC_ALL, "");
  strftime(system_date_buffer, 80, "%x", timeinfo);
  string sysDateFormat(system_date_buffer);
  strftime(iso_date_buffer, 80, "%%Y-%m-%d", timeinfo);
  string isoDateFormat(iso_date_buffer);
  dateArray[0] = sysDateFormat;
  dateArray[1] = iso_date_buffer;
  return Napi::Array::New(env, dateArray); // error here
}
Gerhardh
  • 11,688
  • 4
  • 17
  • 39
kittu
  • 6,662
  • 21
  • 91
  • 185

1 Answers1

3

Using Object type from Napi api worked!

 Napi::Object obj = Napi::Object::New(env);
  obj.Set(Napi::String::New(env, "sysDateFormat"), sysDateFormat);
  obj.Set(Napi::String::New(env, "isoDateFormat"), isoDateFormat);
kittu
  • 6,662
  • 21
  • 91
  • 185