c++ - 从 C++ Node.js 插件渲染文件

标签 c++ node.js v8

我想从 C++ 插件在 node.js 中呈现文件。 我想应用一些文件处理并通过 node.js 将输出呈现给浏览器

这是我的C++代码

    std::ifstream in(filename, std::ios::binary);

    in.seekg (0, in.end);
    int length = in.tellg();
    in.seekg (0, in.beg);

    char * buffer = new char [length];
    in.read (buffer,length);
    in.close();

    return buffer;

以下是为 node.js 添加绑定(bind)的 V8 代码,这里的 buffer 是上述 c++ 代码的输出。

    Local<Function> cb = Local<Function>::Cast(args[1]);
    const unsigned argc = 1;
    Local<Value> argv[argc] = {Local<Value>::New(String::New(buffer))};
    cb->Call(Context::GetCurrent()->Global(), argc, argv);

此代码适用于普通文本文件。读取具有 unicode 字符的文本文件时遇到问题。 例如,

原始文本文件

test start
Billél
last

在 Node 接收时,我会得到

test start
Bill�l
last

类似地,当读取 jpg、png 文件时,输出文件与原始文件不同。 请帮忙。

最佳答案

我也遇到了这个问题。我在 Google 的 V8 示例中找到了一个实现。我发现可以在此处找到正确处理 UTF8 编码文件的示例:

https://code.google.com/p/v8/source/browse/trunk/samples/shell.cc#218

我将源代码改编为:

const char* ReadFile(const char* fileName, int* fileSize)
{
    // reference to c-string version of file
    char *fileBuffer = 0;

    // attempt to open the file
    FILE* fd = fopen(fileName, "rb");

    // clear file size
    *fileSize = 0;

    // file was valid
    if(fd != 0)
    {
       // get size of file
       fseek(fd, 0, SEEK_END);
       *fileSize = ftell(fd);
       rewind(fd);

       // allocate file buffer for file contents
       fileBuffer = (char*)malloc(*fileSize + 1);
       fileBuffer[*fileSize] = 0;

       // copy file contents
       for (int charCount = 0; charCount < *fileSize;)
       {
           int charRead = static_cast<int>(fread(&fileBuffer[charCount], 1, *fileSize - charCount, fd));
           charCount += charRead;
       }

       // close the file
       fclose(fd);
    }

    return fileBuffer;
}

此外,确保在创建 V8 字符串时创建一个 String::Utf8Value .

String::Utf8Value v8Utf8String(...);

然后将 String::Utf8Value 用作 char* 使用以下函数:

https://code.google.com/p/v8/source/browse/trunk/samples/shell.cc#91

关于c++ - 从 C++ Node.js 插件渲染文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18265982/

相关文章:

javascript - Nodejs内存泄漏的几种情况

c++ - 了解 Google 的 V8 C++ 代码库中的继承

javascript - 单个对象的 Node.js 堆内存限制

c++ - 让类存储未知数据

c++ - 在 c++ 或 c 或 Objective-C 中解压缩 split Zip 或/和 multi zip

node.js - readable.on ('end' ,...) 永远不会被解雇

javascript - Express、Passportjs 持久登录不起作用

c++ - SQLite C++ 按名称访问列

c++ - 在 C++ 中,如何在不制作重复代码的情况下为类复制构造函数和赋值运算符提供相同的功能

node.js - Heroku 自定义域不起作用