http://www.nodebeginner.org/index-zh-cn.html#javascript-and-nodejs 看的是这个入门的 但是始终实现不了异步,一直是阻塞的upload执行的时候也要等上10秒,我是在windows7下,用官方的安装包,求指点,代码如下:
index.js
var server = require('./server');
var router = require('./router');
var requestHandlers = require('./requestHandlers');
var handle = {};
handle['/'] = requestHandlers.start;
handle['/start'] = requestHandlers.start;
handle['/upload'] = requestHandlers.upload;
server.start(router.route, handle);
server.js
var http = require('http');
var url = require('url');
function start(route, handle) {
http.createServer(function(request, response){
var pathname = url.parse(request.url).pathname;
console.log('Request for ' + pathname + ' received!')
route(handle, pathname, response);
}).listen(8080);
console.log('Server has started!')
}
exports.start = start;
router.js
function route(handle, pathname, response) {
console.log('About to route a request for ' + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response);
} else {
console.log('No request handler found for ' + pathname);
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('404 Not found!');
response.end();
}
}
exports.route = route;
requestHandlers.js
var exec = require('child_process').exec;
function start(response) {
console.log("Request handler 'start' was called.");
exec('dir', function(error, stdout, stderr){
function sleep(milliSeconds){
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + milliSeconds);
}
sleep(10000);
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write(stdout);
response.end();
});
}
function upload(response) {
console.log("Request handler 'upload' was called.");
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('Hello upload!');
response.end();
}
exports.start = start;
exports.upload = upload;
照理说start方法中exec是异步的,那为什么浏览器调用start后,再调用upload,upload没有立即返回呢?