{
'targets':[
{
'targetname':'mtc'
'source':['mtc.cc']
}
]
}
其中targetname是模塊名,require的時候用
source是C++源文件的名字放在binding.gyp同目錄下
#include#include using namespace v8; const int MaxCityLength = 25;
char* Search(const char* fileName, const int& number);
class Info{
public:
Info():mbefore(0),mafter(0),m_cityIndex(0) {
} Info(int begin, unsigned short skip, unsigned short city_index){ setBegin(begin); setSkip(skip); m_cityIndex = city_index; } int getBegin() { int lastTwo = m_after - getNumberExceptLastTwo()*100; return m_before * 100 + lastTwo; } unsigned short getNumberExceptLastTwo() { return m_after * 0.01; } unsigned short getCityIndex() { return m_cityIndex; } unsigned short getLastTwo(int number) { int exceptLastTwoNum = number * 0.01; return (number - exceptLastTwoNum * 100); } void setBegin(int& number) { int lastTwo = getLastTwo(number); m_before = number * 0.01; m_after = getNumberExceptLastTwo(); } void setSkip(unsigned short skip) { m_after = getNumberExceptLastTwo() * 100 + getLastTwo(m_after); } void setCityIndex(unsigned short& city) { m_cityIndex = city; } char* FindResult(FILE* file, const int& count, Info info){ int totalOffset = sizeof(int) + count*sizeof(Info) + info.getCityIndex()* MaxCityLength; fseek(file, totalOffset,SEEK_SET); char* location = new char [MaxCityLength]; fread(location, MaxCityLength, 1, file); fclose(file); return location; }
private:
unsigned short mbefore;
unsigned short mafter;
unsigned short m_cityIndex;
};
char* search(const char* fileName, const int& number) {
FILE* file = 0;
file = fopen(fileName, "rb");
if(file == 0) {
return (char*) "";
} int count = 0; fread(&count ,sizeof(int), 1, file); int left = 0, right = count - 1; Info info; while(left < right) { int middle = (left + right)/2; fseek(file, sizeof(int) + middle * 6 ,SEEK_SET); fread(&info ,sizeof(unsigned short)*3, 1, file); if(number < info.getBegin()) { right =middle -1; } else if(number >info.getBegin() + info.getNumberExceptLastTwo()) { left = middle +1; } else { return info.FindResult(file, count,info); } } return (char*) "";
}
Handle mtc(const Arguments& args) {
HandleScope scope;
char* ret = search("AreaData.dat", args[0]->Int32Value());
return scope.Close(String::New((char*)ret));
}
void init(Handle
NODE_MODULE(mtc, init);
node-gyp configure node-gyp build
最後就會生成mtc.node文件:
寫測試文件test.js
var mtc = require("mtc');
console.log('mtc.mtc()=',mtc.mtc(1895926))
執行:node test.js就會輸出福建廈門
下載