我实际上得到了你(和我)想要的,没有使用 await、Promises 或任何(外部)库(我们自己的除外)的包含。
这是怎么做的:
我们将制作一个 C++ 模块与 node.js 一起使用,该 C++ 模块函数将发出 HTTP 请求并将数据作为字符串返回,您可以通过以下方式直接使用它:
var myData = newModule.get(url);
您准备好开始了吗?
第 1 步:
在你电脑的其他地方新建一个文件夹,我们只是用这个文件夹来构建 module.node 文件(从 C++ 编译),你可以稍后移动它。
在新文件夹中(我将我的放在 mynewFolder/src 中以进行整理):
npm init
然后
npm install node-gyp -g
现在制作 2 个新文件:
1,调用something.cpp并将此代码放入其中(或根据需要进行修改):
#pragma comment(lib, "urlmon.lib")
#include <sstream>
#include <WTypes.h>
#include <node.h>
#include <urlmon.h>
#include <iostream>
using namespace std;
using namespace v8;
Local<Value> S(const char* inp, Isolate* is) {
return String::NewFromUtf8(
is,
inp,
NewStringType::kNormal
).ToLocalChecked();
}
Local<Value> N(double inp, Isolate* is) {
return Number::New(
is,
inp
);
}
const char* stdStr(Local<Value> str, Isolate* is) {
String::Utf8Value val(is, str);
return *val;
}
double num(Local<Value> inp) {
return inp.As<Number>()->Value();
}
Local<Value> str(Local<Value> inp) {
return inp.As<String>();
}
Local<Value> get(const char* url, Isolate* is) {
IStream* stream;
HRESULT res = URLOpenBlockingStream(0, url, &stream, 0, 0);
char buffer[100];
unsigned long bytesReadSoFar;
stringstream ss;
stream->Read(buffer, 100, &bytesReadSoFar);
while(bytesReadSoFar > 0U) {
ss.write(buffer, (long long) bytesReadSoFar);
stream->Read(buffer, 100, &bytesReadSoFar);
}
stream->Release();
const string tmp = ss.str();
const char* cstr = tmp.c_str();
return S(cstr, is);
}
void Hello(const FunctionCallbackInfo<Value>& arguments) {
cout << "Yo there!!" << endl;
Isolate* is = arguments.GetIsolate();
Local<Context> ctx = is->GetCurrentContext();
const char* url = stdStr(arguments[0], is);
Local<Value> pg = get(url,is);
Local<Object> obj = Object::New(is);
obj->Set(ctx,
S("result",is),
pg
);
arguments.GetReturnValue().Set(
obj
);
}
void Init(Local<Object> exports) {
NODE_SET_METHOD(exports, "get", Hello);
}
NODE_MODULE(cobypp, Init);
现在在同一个目录中创建一个名为something.gyp 的新文件,并将(类似的东西)放入其中:
{
"targets": [
{
"target_name": "cobypp",
"sources": [ "src/cobypp.cpp" ]
}
]
}
现在在 package.json 文件中,添加:"gypfile": true,
现在:在控制台中,node-gyp rebuild
如果它通过整个命令并在最后说“ok”并且没有错误,那么你(几乎)很好,如果没有,那么留下评论..
但如果它有效,则转到 build/Release/cobypp.node(或任何它为您调用的),将其复制到您的主 node.js 文件夹,然后在 node.js 中:
var myCPP = require("./cobypp")
var myData = myCPP.get("http://google.com").result;
console.log(myData);
..
response.end(myData);//or whatever