Friday, September 13, 2019

Node JS - C++ Add On with file reading



Basic C++ code to read the text file is below

#include
using namespace std;

ifstream inFile;

inFile.open("C:\\temp\\datafile.txt");

if (!inFile) {
    cerr << "Unable to open file datafile.txt";
    exit(1);   // call system to stop
}

while (inFile >> x) {
  sum = sum + x;
}

inFile.close();


Now the above can be converted to node module like the below. The same worked without issues


#include "functionexample.h"
#include
#include
using namespace std;
std::string functionexample::hello(){
    return "Hello World";
}
Napi::String functionexample::HelloWrapped(const Napi::CallbackInfo& info)
{
    Napi::Env env = info.Env();
    Napi::String returnValue = Napi::String::New(env, functionexample::hello());
    ifstream inFile;
    inFile.open("test.txt");
    if (!inFile) {
        cout << "Unable to open file";
//        exit(1); // terminate with error
    }
    else {
        cout << "Opened the file";
    }
    return returnValue;
}
Napi::Object functionexample::Init(Napi::Env env, Napi::Object exports)
{
    exports.Set("hello", Napi::Function::New(env, functionexample::HelloWrapped));
    return exports;
}




References:
http://www.fredosaurus.com/notes-cpp/io/readtextfile.html

No comments:

Post a Comment