Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <node.h>
- #include <vector>
- #include <string>
- #include <sstream>
- #include <iostream>
- using namespace v8;
- short tagDetect(char * ptr){
- if (*ptr == '/') {
- return 0;
- }
- if (*ptr == 'p') {
- return 1;
- }
- if (*(ptr + 1) == '2' || *(ptr + 1) == '3')
- return 2;
- return -1;
- }
- Handle<Value> Callback(const Arguments& args) {
- HandleScope scope;
- if (!args[0]->IsString() || !args[1]->IsFunction()) {
- return ThrowException(Exception::TypeError(
- String::New("Invalid arguments! First parameter must be [string], second must be a callback [function].")));
- }
- Local<Function> callback = Local<Function>::Cast(args[1]);
- String::Utf8Value param1(args[0]->ToString());
- std::string input = std::string(*param1);
- // </p>\n<p> -> ""
- static Persistent<String> data_symbol = NODE_PSYMBOL("data");
- static Persistent<String> tag_symbol = NODE_PSYMBOL("tag");
- /* ALGORITHM */
- std::string::size_type pos = 0;
- int openPos;
- short tagID, lastTag, id = 0;
- Local<Array> nodes = Array::New();
- while ((pos = input.find('<', pos)) != std::string::npos) {
- pos++;
- tagID = tagDetect(&input[pos]);
- switch (tagID) {
- case 0:
- if (tagID = tagDetect(&input[pos + 1]) == lastTag && (pos - openPos > 10 || lastTag != 1)) {
- Local<Object> node_obj = Object::New();
- node_obj->Set(data_symbol, String::New(input.substr(openPos + (lastTag > 1 ? 3 : 2), pos - openPos - (lastTag > 1 ? 3 : 2) - 1).c_str()));
- node_obj->Set(tag_symbol, Integer::New(lastTag));
- nodes->Set(id, node_obj);
- id++;
- }
- break;
- case 1:
- case 2:
- case 3:
- openPos = pos;
- lastTag = tagID;
- break;
- }
- }
- const unsigned argc = 2;
- Local<Value> argv[argc] = {
- Local<Value>::New(Null()),
- nodes
- };
- callback->Call(Context::GetCurrent()->Global(), argc, argv);
- return Undefined();
- }
- void RegisterModule(Handle<Object> target) {
- target->Set(String::NewSymbol("parse"),
- FunctionTemplate::New(Callback)->GetFunction());
- }
- NODE_MODULE(smartparser, RegisterModule);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement