我想从 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/