Node.js是一個Javascript開源的服務器環境,運行在各類平臺上(Windows,Linux,Unix,Mac OS X等)。
1.nodejs下載地址:http://nodejs.cn/download/ 下載windows版本,直接運行安裝便可javascript
2.運行nodejs腳本經過命令執行 node test.js (這裏我使用IDE: Sublime Text3 )
html
3.NPM是隨同的NodeJS一塊兒安裝的包管理工具java
npm install <模塊名稱> //Ex:redis mysql ... //安裝mysql模塊 npm install mysql
使用模塊 var mysql= require('mysql'); //不區分大小寫(‘MySql’)node
4.鏈接MySQLmysql
1 //鏈接MySQL
2 var mysql = require('MYSql');//引入
3 var TABLE="bookuser"
4 var connection = mysql.createConnection({ 5 host : '127.0.0.1', //主機地址 6 user : 'root', //用戶名 7 password : '123456', //密碼 8 port: '3306', //端口 9 database:'test' //數據庫名 10 });
更多參數android
host | 主機地址 (默認:localhost) |
user | 用戶名 |
password | 密碼 |
port | 端口號 (默認:3306) |
database | 數據庫名 |
charset | 鏈接字符集(默認:'UTF8_GENERAL_CI',注意字符集的字母都要大寫) |
localAddress | 此IP用於TCP鏈接(可選) |
socketPath | 鏈接到unix域路徑,當使用 host 和 port 時會被忽略 |
timezone | 時區(默認:'local') |
connectTimeout | 鏈接超時(默認:不限制;單位:毫秒) |
stringifyObjects | 是否序列化對象 |
typeCast | 是否將列值轉化爲本地JavaScript類型值 (默認:true) |
queryFormat | 自定義query語句格式化方法 |
supportBigNumbers | 數據庫支持bigint或decimal類型列時,須要設此option爲true (默認:false) |
bigNumberStrings | supportBigNumbers和bigNumberStrings啓用 強制bigint或decimal列以JavaScript字符串類型返回(默認:false) |
dateStrings | 強制timestamp,datetime,data類型以字符串類型返回,而不是JavaScript Date類型(默認:false) |
debug | 開啓調試(默認:false) |
multipleStatements | 是否許一個query中有多個MySQL語句 (默認:false) |
flags | 用於修改鏈接標誌 |
ssl | 使用ssl參數(與crypto.createCredenitals參數格式一至)或一個包含ssl配置文件名稱的字符串,目前只捆綁Amazon RDS的配置文件 |
更多說明可參見:https://github.com/mysqljs/mysqlgit
SQL語句, userModSql_Params 的值分別對應‘?’github
1 //改 update 2 var userModSql = 'UPDATE bookuser SET username = ?,userpass = ? WHERE id = ?'; 3 var userModSql_Params = ['Hello World','456789',13]; 4 connection.query(userModSql,userModSql_Params,function (err, result) { 5 if(err){ 6 console.log('[UPDATE ERROR] - ',err.message); 7 return; 8 } 9 console.log('----------UPDATE-------------'); 10 console.log('UPDATE affectedRows',result.affectedRows); 11 console.log('******************************'); 12 }); 13 connection.end(); 14 15 //增 add 16 var userAddSql = 'INSERT INTO bookuser(id,username,userpass) VALUES(0,?,?)'; 17 var userAddSql_Params = ['Wilson', '123456']; 18 connection.query(userAddSql,userAddSql_Params,function (err, result) { 19 if(err){ 20 console.log('[INSERT ERROR] - ',err.message); 21 return; 22 } 23 console.log('-------INSERT----------'); 24 console.log('INSERT ID:',result.insertId); 25 console.log('INSERT ID:',result); 26 console.log('#######################'); 27 }); 28 connection.end();
也可將參數拼接在sql語句中redis
1 //存 insert 2 function insert(title01,url01,date01,date02){ 3 var userAddSql = 'INSERT INTO wechart03(id, title,url,pubtime,nowtime) SELECT 0,"'+title01+'", "'+url01+'", "'+date01+'","'+date02+'" FROM DUAL WHERE NOT EXISTS(SELECT * FROM wechart03 WHERE url = "'+url01+'")'; 4 connection.query(userAddSql,function (err, result) { 5 if(err){ 6 console.log('[INSERT ERROR] - ',err.message); 7 return; 8 } 9 console.log('-------INSERT----------'); 10 console.log('INSERT ID:',result); 11 console.log('#######################'); 12 }); 13 //connection.end(); 14 } 15 //改 update 16 function update(read,like,url02){ 17 var userModSql = 'UPDATE wechart03 SET readnum = "'+read+'",likenum = "'+like+'" WHERE url = "'+url02+'"'; 18 //var userModSql = 'UPDATE wechart02 SET readnum = ?,likenum = ? WHERE url = ?'; 19 //var userModSql_Params = [read,like,url02]; 20 connection.query(userModSql,function (err, result) { 21 if(err){ 22 console.log('[UPDATE ERROR] - ',err.message); 23 return; 24 } 25 console.log('----------UPDATE-------------'); 26 console.log('UPDATE affectedRows',result.affectedRows); 27 console.log('******************************'); 28 }); 29 //connection.end(); 30 }
5.鏈接Redissql
1 //redis 鏈接 2 var redis = require('redis'), 3 RDS_PORT = 6379, //端口號 4 RDS_HOST = '127.0.0.1', //服務器IP 5 RDS_PWD = '123', //密碼 6 // RDS_OPTS = {}, //設置項 7 8 //建立redis鏈接對象 9 client = redis.createClient(RDS_PORT,RDS_HOST); 10 11 // 驗證鏈接 12 client.auth(RDS_PWD,function (){ 13 console.log('鏈接redis成功!'); 14 }); 15 //Redis存值 16 client.set('test01','Redis',function(err,response){ 17 console.log(err,response); 18 }); 19 //Redis取值 20 client.get('test01',function(err,response){ 21 console.log(err,response); 22 });
6.在 Node.js 中,建立一個模塊並引用
在test01.js中定義以下函數
1 module.exports = function Print() { 2 var name; 3 this.setName = function(thyName) { 4 name = thyName; 5 }; 6 this.sayName = function() { 7 console.log('say ' + name); 8 }; 9 };
在test02.js中調用
1 var p = require('./test01'); 2 var a = new p(); 3 a.setName('ABCD'); 4 a.sayName();
控制檯輸出
say ABCD
7.Nodejs GET請求
1 var url = "https://mp.weixin.qq.com/mp/profile_ext?action=home" 2 + "&__biz="+wechartCookie.biz 3 + "&scene=124&devicetype=android-19" 4 + "&version="+wechartCookie.version+"&lang=zh_CN&nettype=WIFI&a8scene=3&pass_ticket=" 5 + wechartCookie.passticket + "&wx_header=1"; 6 console.log(url); 7 var request = require('request'); 8 request({ 9 url: url, 10 json: true, 11 headers: { 12 "Host": "mp.weixin.qq.com", 13 "x-wechat-uin":wechartCookie.uin, 14 "x-wechat-key":wechartCookie.key, 15 "User-Agent":"Mozilla/5.0 (Linux; Android 4.4.2; M688C Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36 MicroMessenger/6.5.23.1180 NetType/WIFI Language/zh_CN", 16 "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 17 "Cookie":wechartCookie.cookies, 18 "X-Requested-With":"com.tencent.mm", 19 }, 20 },function (error, response, html) { 21 if (!error && response.statusCode == 200) { 22 //..... 23 }
8.POST請求
1 var url2 = "https://mp.weixin.qq.com/mp/getappmsgext?__biz=" + biz + "&mid=" + mid + "&sn=" + sn 2 + "&idx=" + idx + "&scene=" + scene + "&f=json&appmsg_type=9&appmsg_token=" + wechartcook.appmsgtoken 3 + "&x5=0&f=json&is_only_read=1&pass_ticket="+wechartcook.passticket+"&is_temp_url=0&is_need_reward=0&both_ad=0&reward_uin_count=0" 4 + "&version=/mmbizwap/zh_CN/htmledition/js/appmsg/index3a9713.js&is_need_ad=1&msg_daily_idx=1" 5 + "&is_original=0&uin=777&key=777"; 6 // console.log(url2); 7 8 var request=require('request'); 9 var options = { 10 url: url2, 11 method: "POST", 12 headers: { 13 "Host": "mp.weixin.qq.com", 14 "Connection":"keep-alive", 15 "Origin":"https://mp.weixin.qq.com", 16 "X-Requested-With":"XMLHttpRequest", 17 //"User-Agent":"Mozilla/5.0 (Linux; Android 4.4.2; M688C Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36MicroMessenger/6.5.23.1180 NetType/WIFI Language/zh_CN", 18 "User-Agent":"Mozilla/5.0 (Linux; Android 5.1.1; SM-G9350 Build/LMY48Z) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Safari/537.36 MicroMessenger/6.6.7.1321(0x26060737) NetType/WIFI Language/zh_CN", 19 "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8", 20 "Accept":"*/*", 21 //"Accept-Encoding":"gzip,deflate", 22 "Accept-Language":"zh-CN,en-US;q=0.8", 23 "Referer":url2, 24 "Cookie":wechartcook.cookies, 25 } 26 } 27 28 request(options, function (error, response, body){ 29 if (!error && response.statusCode == 200) { 30 31 //....... 32 33 }
第三個參數 返回值(html body)。
9.Nodejs 定時器
1 function func(){ 2 console.log('dosomething'); 3 } 4 //定時器1 執行一次 5 var t =setTimeout(func, 2000); 6 //清除定時器 7 clearTimeout(t); 8 9 //定時器2 週期執行 10 var t =setInterval(func, 2000); 11 //清除定時器 12 clearInterval(t);
10.建立子進程 child_process.fork()方法 建立一個子進程。
1 //定時器,每隔3分鐘執行一次 2 var child_process = require('child_process'); 3 setInterval(function (){ 4 //建立子進程 5 child_process.fork('./demo.js', { 6 }); 7 }, 1000*60*3);
W3schools.com 瞭解更多