微信小程序 Node.js (基礎(chǔ)十一) 全局對象
__filename 腳本絕對路徑表示當(dāng)前正在執(zhí)行的腳本的文件名。它將輸出文件所在位置的絕對路徑,且和命令行參數(shù)所指定的文件名不一定相同。 如果在模塊中,返回的值是模塊文件的路徑。 console.log(__filename); // C:\Users\admin\main.js
__dirname 腳本所在的目錄表示當(dāng)前執(zhí)行腳本所在的目錄。 console.log(__dirname); // C:\Users\admin
setTimeout(cb, ms) 執(zhí)行一次函數(shù)cb全局函數(shù)在指定的毫秒(ms)數(shù)后執(zhí)行指定函數(shù)(cb)。 setTimeout() 只執(zhí)行一次指定函數(shù)。 返回一個代表定時器的句柄值。
function printHello(){
console.log( "Hello, World!");
}
// 兩秒后執(zhí)行以上函數(shù)
setTimeout(printHello, 2000);
clearTimeout(t) 停止函數(shù)tclearTimeout( t ) 全局函數(shù)用于停止一個之前通過 setTimeout() 創(chuàng)建的定時器。 參數(shù) t 是通過 setTimeout() 函數(shù)創(chuàng)建的定時器。
function printHello(){
console.log( "Hello, World!");
}
// 兩秒后執(zhí)行以上函數(shù)
var t = setTimeout(printHello, 2000);
clearTimeout(t)
setInterval(cb, ms) 不停地調(diào)用函數(shù)cb
function printHello(){
console.log( "Hello, World!");
}
// 兩秒后執(zhí)行以上函數(shù)
setInterval(printHello, 2000);
process 一個與操作系統(tǒng)的簡單接口process 是一個全局變量,即 global 對象的屬性。 它用于描述當(dāng)前Node.js 進(jìn)程狀態(tài)的對象,提供了一個與操作系統(tǒng)的簡單接口。通常在你寫本地命令行程序的時候,少不了要和它打交道。
微信小程序 Node.js (基礎(chǔ)十二) GET/POST請求
var http = require("http")
var url = require("url")
var util = require("util")
var querystring = require("querystring")
function start(){
// 獲取GET請求內(nèi)容
this.getRequest = function(){
http.createServer(function(request,response){
var pathname = url.parse(request.url).pathname
console.log(pathname)
response.writeHead(200,{"Content-Type":"text/plain"})
response.write("Hello World")
// http://127.0.0.1:8888/user?name=12456
// util.inspect(object) 將任意對象轉(zhuǎn)換 為字符串
// url.parse 將一個URL字符串轉(zhuǎn)換成對象并返回
response.end(util.inspect(url.parse(request.url,true)));
response.end(url.parse(request.url,true).query.name);
}).listen(8888)
}
// 獲取POST請求內(nèi)容
this.postRequst = function (){
http.createServer(function (req, res) {
var body = "";
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
// 設(shè)置響應(yīng)頭部信息及編碼
res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
// {"name":"123","address":"123123"}
console.log(body)
// querystring.parse 將一個字符串反序列化為一個對象
// { '{"name":"123","address":"123123"}': '' }
console.log(querystring.parse(body))
// JSON.parse(string) 將字符串轉(zhuǎn)為JS對象。
// JSON.stringify(obj) 將JS對象轉(zhuǎn)為字符串。
// { name: '123', address: '123123' }
console.log(JSON.parse(body))
body = JSON.parse(body)
res.write("網(wǎng)站名:" + body.name);
res.write("
");
res.write("網(wǎng)站 URL:" + body.address);
res.end();
});
}).listen(3000);
}
}
module.exports = start
var Util = require("./util")
var util = new Util ();
util.postRequst();
|