Use nodejs to Access ActiveX objects. _ Javascript skills

Source: Internet
Author: User
Someone asked, "If nodejs is used to access sqlserver ?" I searched for information and found two solutions: the reason for using the third-party nodejs plug-in
Someone asked, "If nodejs is used to access SQL server ?"
After finding the information, I found two solutions: Use the third-party nodejs plug-in: https://github.com/orenmazor/node-tds、to use the adodb.connectionactivexobject.
Refer:
Http://stackoverflow.com/questions/857670/how-to-connect-to-sql-server-database-from-javascript
Http://stackoverflow.com/questions/4728385/connecting-to-a-remote-microsoft-sql-server-from-node-js
If ActiveX is used, nodejs will be omnipotent in Windows, similar to asp. Then how do they communicate? You have to try it.
After
Ideas
Using nodejsto indirectly Access ActiveX through cscript.exe (windows Script process)
Cscript can parse two types of scripts: jscript and vbscript, which are undoubtedly chosen for development for convenience of maintenance.
Reference: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cscript_overview.mspx? Mfr = true
Problems to be Solved
1. Cross-process communication
The new version of nodejs adds sub-process operations. Cross-process communication is not a problem.
Http://nodejs.org/docs/latest/api/all.html#child_Processes

The Code is as follows:


Var util = require ('til '),
Exec = require('child_process'cmd.exe c,
Child;


Child = exec ('cat *. js bad_file | wc-l ',
Function (error, stdout, stderr ){
Console. log ('stdout: '+ stdout );
Console. log ('stderr: '+ stderr );
If (error! = Null ){
Console. log ('exec error: '+ error );
}
});


For example, we can get the output content stdout from the console!


2. database access related ActiveX, ADODB. Connection
Reference: http://msdn.microsoft.com/en-us/library/windows/desktop/aa746471%28v=vs.85%29.aspx

The Code is as follows:


Var connection = new ActiveXObject ("ADODB. Connection ");
Var result = 'OK ';
Try {
Connection. Open ("Provider = Microsoft. Jet. OLEDB.4.0; Data Source =" + params. accessfile );
Connection. Execute (params. SQL );
} Catch (ex ){
Result = ex. message;
}
Return {
Result: result
};


Connection. Open (connectionString), the link string parameter can be set to access SQL server.
Reference: http://www.connectionstrings.com/sql-server-2005
3. For ease of maintenance, the cscript and nodejs scripts are combined to use typeof exports to determine the current running environment.
4. character encoding cscript Code uses ascii Encoding
Non-ascii characters are encoded with "uHHHH" Unicode.
5. Escape the command line characters. Double quotation marks and percent signs are of special significance in the command line.
Base64 encoding is used for parameter passing to avoid conflict
In the cscript environment, MSXML2.DOMDocument supports base64 encoding/decoding.

The Code is as follows:


Function base64Decode (base64 ){
Var xmldom = new ActiveXObject ("MSXML2.DOMDocument ");
Var adostream = new ActiveXObject ("ADODB. Stream ");
Var temp = xmldom. createElement ("temp ");
Temp. dataType = "bin. base64 ";
Temp. text = base64;


Adostream. Charset = "UTF-8 ";
Adostream. Type = 1; // 1 = adTypeBinary 2 = adTypeText
Adostream. Open ();
Adostream. Write (temp. nodeTypedValue );
Adostream. Position = 0;
Adostream. Type = 2; // 1 = adTypeBinary 2 = adTypeText
Var result = adostream. ReadText (-1); //-1 = adReadAll
Adostream. Close ();
Adostream = null;
Xmldom = null;
Return result;
}



Summary
Call Process
1. Create a sub-process and pass the encoded parameters;
2. After the sub-process is processed, the data is formatted in JSON format and output to the console. (The sub-process stops automatically)
3. read data from the console and execute the callback function.


Advantages
1. Enable nodejs to Access ActiveX objects;
2. Simple implementation and convenient development and maintenance.


Disadvantage
1. It can only run on Windows platforms;
2. Data Encoding/decoding consumes more cpu resources;
3. Each call requires a sub-process to be re-connected. (Improvements)
Summary
1. It is practical;
2. Cross-process communication performance can be further explored.
Module code:

The Code is as follows:


Var Access = {
Create: function (params ){
Var fso = new ActiveXObject ("Scripting. FileSystemObject ");
Var result = 'OK ';
If (! Fso. FileExists (params. accessfile )){
Var adoxcatalog = new ActiveXObject ("ADOX. Catalog ");
Try {
Adoxcatalog. Create ("Provider = Microsoft. Jet. OLEDB.4.0; Data Source =" + params. accessfile );
} Catch (ex ){
Result = ex. message;
Return;
}
Adoxcatalog = null;
} Else {
Result = 'exists ';
}
Return {
Result: result
};
},
ExistsTable: function (params ){
Var connection = new ActiveXObject ("ADODB. Connection ");
Var result = 'OK', exists = false;
Try {
Connection. Open ("Provider = Microsoft. Jet. OLEDB.4.0; Data Source =" + params. accessfile );
Var recordset = connection. OpenSchema (20/* adSchemaTables */);
Recordset. MoveFirst ();
While (! Recordset. EOF ){
If (recordset ("TABLE_TYPE") = "TABLE" & recordset ("TABLE_NAME") = params. tablename ){
Exists = true;
Break;
}
Recordset. MoveNext ();
}
Recordset. Close ();
Recordset = null;
} Catch (ex ){
Result = ex. message;
}
Return {
"Result": result,
"Exists": exists
};
},
Execute: function (params ){
Var connection = new ActiveXObject ("ADODB. Connection ");
Var result = 'OK ';
Try {
Connection. Open ("Provider = Microsoft. Jet. OLEDB.4.0; Data Source =" + params. accessfile );
Connection. Execute (params. SQL );
} Catch (ex ){
Result = ex. message;
}
Return {
Result: result
};
},
Query: function (params ){
Var connection = new ActiveXObject ("ADODB. Connection ");
Var result = 'OK', records = [];
Try {
Connection. Open ("Provider = Microsoft. Jet. OLEDB.4.0; Data Source =" + params. accessfile );
Var recordset = new ActiveXObject ("ADODB. Recordset ");
Recordset. Open (params. SQL, connection );
Var fields = [];
Var enumer = new Enumerator (recordset. Fields );
For (;! Enumer. atEnd (); enumer. moveNext ()){
Fields. push (enumer. item (). name );
}
Recordset. MoveFirst ();
While (! Recordset. EOF ){
Var item = {};
For (var I = 0; I <fields. length; I ++ ){
Var fieldname = fields [I];
Item [fieldname] = recordset (fieldname). value;
}
Records. push (item );
Recordset. MoveNext ();
}
Recordset. Close ();
Recordset = null;
} Catch (ex ){
Result = ex. message;
}
Return {
Result: result,
Records: records
};
}
};
If (/^ u/. test (typeof exports) {// cscript
Void function (){
// From http://tangram.baidu.com/api.html#baidu.json
Var JSON = {
Stringify: (function (){
/**
* Sequence table to be escaped during string processing
* @ Private
*/
Var escapeMap = {
"\ B": '\ B ',
"\ T": '\ t ',
"\ N": '\ n ',
"\ F": '\ F ',
"\ R": '\ R ',
'"':'\\"',
"\\":'\\\\'
};
/**
* String serialization
* @ Private
*/
Function encodeString (source ){
If (/["\ x00-\ x1f]/. test (source )){
Source = source. replace (
/["\ X00-\ x1f]/g,
Function (match ){
Var c = escapeMap [match];
If (c ){
Return c;
}
C = match. charCodeAt ();
Return "\ u00"
+ Math. floor (c/16). toString (16)
+ (C % 16). toString (16 );
});
}
Return '"' + source + '"';
}
/**
* Array serialization
* @ Private
*/
Function encodeArray (source ){
Var result = ["["],
L = source. length,
PreComma, I, item;
For (I = 0; I <l; I ++ ){
Item = source [I];
Switch (typeof item ){
Case "undefined ":
Case "function ":
Case "unknown ":
Break;
Default:
If (preComma ){
Result. push (',');
}
Result. push (JSON. stringify (item ));
PreComma = 1;
}
}
Result. push ("]");
Return result. join ("");
}
/**
* Zero completion during processing of date serialization
* @ Private
*/
Function pad (source ){
Return source <10? '0' + source: source;
}
/**
* Date serialization
* @ Private
*/
Function encodeDate (source ){
Return '"' + source. getFullYear () + "-"
+ Pad (source. getMonth () + 1) + "-"
+ Pad (source. getDate () + "T"
+ Pad (source. getHours () + ":"
+ Pad (source. getMinutes () + ":"
+ Pad (source. getSeconds () + '"';
}
Return function (value ){
Switch (typeof value ){
Case 'undefined ':
Return 'undefined ';
Case 'number ':
Return isFinite (value )? String (value): "null ";
Case 'string ':
Return encodeString (value). replace (/[^ \ x00-\ xff]/g, function (all ){
Return "\ u" + (0x10000 + all. charCodeAt (0). toString (16). substring (1 );
});
Case 'boolean ':
Return String (value );
Default:
If (value = null ){
Return 'null ';
}
If (value instanceof Array ){
Return encodeArray (value );
}
If (value instanceof Date ){
Return encodeDate (value );
}
Var result = ['{'],
Encode = JSON. stringify,
PreComma,
Item;
For (var key in value ){
If (Object. prototype. hasOwnProperty. call (value, key )){
Item = value [key];
Switch (typeof item ){
Case 'undefined ':
Case 'unknown ':
Case 'function ':
Break;
Default:
If (preComma ){
Result. push (',');
}
PreComma = 1;
Result. push (encode (key) + ':' + encode (item ));
}
}
}
Result. push ('}');
Return result. join ('');
}
};
})(),
Parse: function (data ){
Return (new Function ("return (" + data + ")"))();
}
}
// Http://blog.csdn.net/cuixiping/article/details/409468
Function base64Decode (base64 ){
Var xmldom = new ActiveXObject ("MSXML2.DOMDocument ");
Var adostream = new ActiveXObject ("ADODB. Stream ");
Var temp = xmldom. createElement ("temp ");
Temp. dataType = "bin. base64 ";
Temp. text = base64;
Adostream. Charset = "UTF-8 ";
Adostream. Type = 1; // 1 = adTypeBinary 2 = adTypeText
Adostream. Open ();
Adostream. Write (temp. nodeTypedValue );
Adostream. Position = 0;
Adostream. Type = 2; // 1 = adTypeBinary 2 = adTypeText
Var result = adostream. ReadText (-1); //-1 = adReadAll
Adostream. Close ();
Adostream = null;
Xmldom = null;
Return result;
}
WScript. StdOut. Write (' ');
Var method = Access [WScript. Arguments (0)];
Var result = null;
If (method ){
Result = method (JSON. parse (base64Decode (WScript. Arguments (1 ))));
}
WScript. StdOut. Write (JSON. stringify (result ));
WScript. StdOut. Write (' ');
}();
} Else {// nodejs
Void function (){
Function json4stdout (stdout ){
If (! Stdout) return;
Var result = null;
String (stdout). replace (/ ([\ S \ S] +) <\/json>/, function (){
Result = JSON. parse (arguments [1]);
});
Return result;
}
Var util = require ('util'), exec = require('child_process'cmd.exe c;
For (var name in Access ){
Exports [name] = (function (funcname ){
Return function (params, callback ){
Console. log ([funcname, params]);
Exec (
Util. format (
'Cscript.exe/e: jscript "% s" ', _ filename,
Funcname,
(New Buffer (JSON. stringify (params). toString ('base64 ')
),
Function (error, stdout, stderr ){
If (error! = Null ){
Console. log ('exec error: '+ error );
Return;
}
Console. log ('stdout: '+ stdout );
Callback & callback (json4stdout (stdout ));
}
);
}
}) (Name );
}
}();
}


Call code:

The Code is as follows:


Var access = require ('./access. js ');
Var util = require ('til ');
Var accessfile = 'demo. mdb ';
Access. create ({accessfile: accessfile}, function (data ){
Console. log (data );
});
Access. existsTable ({accessfile: accessfile, tablename: 'Demo'}, function (data ){
If (data. result = 'OK '&&! Data. exists ){
Access.exe cute ({
Accessfile: 'demo. mdb ',
SQL: "CREATE TABLE demo (id Counter Primary key, data Text (100 ))"
});
}
});
Access.exe cute ({
Accessfile: 'demo. mdb ',
SQL: util. format ("INSERT INTO demo (data) VALUES ('zswang passed! % S') ", + new Date)
}, Function (data ){
Console. log (data );
});
Access. query ({
Accessfile: 'demo. mdb ',
SQL: "SELECT * FROM demo"
}, Function (data ){
Console. log (data );
});


Latest code: http://code.google.com/p/nodejs-demo/source/browse/#svn%2Ftrunk%2Fdatabase

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.