Fork me on GitHub
usa flag
Read this tutorial in english
spanish flag
Lee este tutorial en Español
korean flag
이 튜토리얼을 한글로 보세요
chinese flag
阅读本书中文版
traditional chinese flag
閱讀本書繁體中文版
russian flag
Читать этот учебник на русском
vietnamese flag
Đọc bằng tiếng Việt
   

The perfect introduction plus the perfect reference in one bundle!

LeanBundle currently offers
the final version of
The Node Beginner Book
plus Pedro Teixeira's excellent
Hands-on Node.js for only

$9.99
(regular price $21.98)

226 pages in total
PDF, ePub & MOBI
Direct download
Free updates

Buy this
bundle now

Nodeビギナーズブック

A Node.js tutorial by Manuel Kiessling
Translated by Yuki Kawashima

本書について


 Node.js  JavaScript  Hello World  


   Node.js  2012212  

Node.js0.6.10  


RubyPythonPHPJava  JavaScriptNode.js    

     

JavaScript  


Web  WebWeb  

         

Node.js使JavaScript  JavaScript  

Hello World  Node.js  

     

JavaScript    

 NodeBeginnerBook Github    
目次

JavaScriptとNode.js

JavaScriptと貴方


 JavaScript    

HTMLHTML  JavaScript  Web使  

WebPHP  RubyJava    

JavaScriptjQueryPrototype  JavaScriptwindow.open()    

jQueryWeb  JavaScript    

Node.jsJavaScript  

JavaScript  Node.js    JavaScript  

JavaScript2  3(90DHTML  jQuery)  JavaScriptJavaScript  使  

 使    

   

 


JavaScript  

 Web12  JavaScriptNode.js  JavaScript  

   

Node.js  

JavaScript


JavaScript        JavaScript使  JavaScript  

Node.js  Node.jsJavaScript  

JavaScript  Node.js  GoogleV8 VM  V8 VMGoogle Chrome使JavaScript  

Node.js便  1  

Node.js2  

使Node.js    

"Hello World"


OK  Node.jsHello World  

helloworld.js  Hello World:  
console.log("Hello World");

Node.js:  
node helloworld.js

Hello World  

退  

Node.jsWeb

 


:  


Web使  

http://domain/start    

 http://domain/upload    


Google    

   Node.js    


   


WebHTTP  

URL    

   

POST  使    

URL  URL      

   


PHP    Apache HTTPmod_php5  
WebHTTP  PHP  

nodeNode.js  HTTP  WebWeb  

 Node.js  

HTTP  

 

HTTP


Node.js    
1Web  Node.jsHTTP1    

使    

Node.js  使    

 HTTP  

index.js  server.js  

server.js  :  
var http = require("http");

http
.createServer(function(request, response) {
  response
.writeHead(200, {"Content-Type": "text/plain"});
  response
.write("Hello World");
  response
.end();
}).listen(8888);

HTTP    Node.js:  
node server.js

 http://localhost:8888/    Hello WorldWeb  

   

HTTP


 

httprequire()  Node.jshttp  http  

httpcreateServer  listen  listenHTTP  

http.createServer  

8888:  
var http = require("http");

var server = http.createServer();
server
.listen(8888);

HTTP8888  ()  

(PHP)  createServer()1  

createServer() ()  JavaScript  


:  
function say(word) {
  console
.log(word);
}

function execute(someFunction, value) {
  someFunction
(value);
}

execute
(say, "Hello");

sayexecute1  saysay  

sayexecute  someFunction  execute()someFunction()    

say1  executesomeFunction    

   :  
function execute(someFunction, value) {
  someFunction
(value);
}

execute
(function(word){ console.log(word) }, "Hello");

execute1execute    

 (anonymous function)  

JavaScript    JavaScript        

HTTP


HTTP  
var http = require("http");

http
.createServer(function(request, response) {
  response
.writeHead(200, {"Content-Type": "text/plain"});
  response
.write("Hello World");
  response
.end();
}).listen(8888);

:  createServer  

:  
var http = require("http");

function onRequest(request, response) {
  response
.writeHead(200, {"Content-Type": "text/plain"});
  response
.write("Hello World");
  response
.end();
}

http
.createServer(onRequest).listen(8888);

:   


a) ()b) Node.js    

 Felix Geisendörfer  Understanding node.js    

Node.js      WebNode.js  

http.createServer    HTTP  

:     

PHP:  HTTP  (Apache)Web  PHP  

8888  Node.js    

 Node.js/JavaScript    

   

   

   

 Felix  

使  HTTP  :  
var http = require("http");

function onRequest(request, response) {
  console
.log("Request received.");
  response
.writeHead(200, {"Content-Type": "text/plain"});
  response
.write("Hello World");
  response
.end();
}

http
.createServer(onRequest).listen(8888);

console
.log("Server has started.");

onRequest()  console.log  HTTP  

(node server.js)  Server has started.  (http://localhost:8888)    Request received.  

JavaScript :-)  

(Request received.2  http://localhost:8888/   favicon)  


OK  onRequest()  

onRequest()2  requestresponse  

使  HTTP  ()  

:  response.writeHead()使  HTTP200content-typeHTTP  response.write()使  Hello WorldHTTP  

response.end() 

request使    


OK  server.jsHTTP  使  index.js  (server.jsHTTP)  

server.jsindex.js使  Node.js  

:  
var http = require("http");

...

http
.createServer(...);

Node.jshttp  require使  

 http使  

 :  
var foo = require("http");

...

foo
.createServer(...);

Node.js使  使  

server.js  

   export  

exportHTTP:    

start  export:  
var http = require("http");

function start() {
 
function onRequest(request, response) {
    console
.log("Request received.");
    response
.writeHead(200, {"Content-Type": "text/plain"});
    response
.write("Hello World");
    response
.end();
 
}

  http
.createServer(onRequest).listen(8888);
  console
.log("Server has started.");
}

exports
.start = start;

server.js  index.jsHTTP  

index.js:  
var server = require("./server");

server
.start();

使:  requireexport使  

 :  
node index.js

   

HTTP     URL  

onRequest()        

HTTP   router  


URLGETPOST  (  3  )  

HTTPURLGETPOST    ()  HTTP  

onRequest()request    Node.js  urlquerystring  

url  URL()  querystring:  
                               url.parse(string).query
                                           |
           url.parse(string).pathname      |
                       |                   |
                       |                   |
                     ------ -------------------
http://localhost:8888/start?foo=bar&hello=world
                                ---       -----
                                 |          |
                                 |          |
              querystring(string)["foo"]    |
                                            |
                         querystring(string)["hello"]

querystring使  POST    

onRequest()  URL:  
var http = require("http");
var url = require("url");

function start() {
 
function onRequest(request, response) {
   
var pathname = url.parse(request.url).pathname;
    console
.log("Request for " + pathname + " received.");
    response
.writeHead(200, {"Content-Type": "text/plain"});
    response
.write("Hello World");
    response
.end();
 
}

  http
.createServer(onRequest).listen(8888);
  console
.log("Server has started.");
}

exports
.start = start;

URL     ()使URL    

 /startURL  /uploadURL    

OK  router.js  :  
function route(pathname) {
  console
.log("About to route a request for " + pathname);
}

exports
.route = route;

 OK    

HTTP        (Dependency Injection:     Martin Fowler  )  

start()  使:  
var http = require("http");
var url = require("url");

function start(route) {
 
function onRequest(request, response) {
   
var pathname = url.parse(request.url).pathname;
    console
.log("Request for " + pathname + " received.");

    route
(pathname);

    response
.writeHead(200, {"Content-Type": "text/plain"});
    response
.write("Hello World");
    response
.end();
 
}

  http
.createServer(onRequest).listen(8888);
  console
.log("Server has started.");
}

exports
.start = start;

index.js:  
var server = require("./server");
var router = require("./router");

server
.start(router.route);

 

(node indes.js)URL  HTTP使  :  
bash$ node index.js
Request for /foo received.
About to route a request for /foo

(/favicon.ico)  


 

 :  indexrouter  route  

使    

     

   

Steve Yegge  Execution in the Kingdom of Nouns        


HTTP    

   /upload/start  

     

 使  

 -        :  
function start() {
  console
.log("Request handler 'start' was called.");
}

function upload() {
  console
.log("Request handler 'upload' was called.");
}

exports
.start = start;
exports
.upload = upload;

   

:      使使      

     

2    URL    if request == x then call handler y    

(URL)    

JavaScript  使  

URL  http://msdn.microsoft.com/en-us/magazine/cc163419.aspx  :  


C++C#       ()  JavaScript  JavaScript  JavaScript    


JavaScript     -   

OK  route()  

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);

handle()  使    

 URL:  /requestHandlers.start  /start/start    

   server.js使:  
var http = require("http");
var url = require("url");

function start(route, handle) {
 
function onRequest(request, response) {
   
var pathname = url.parse(request.url).pathname;
    console
.log("Request for " + pathname + " received.");

    route
(handle, pathname);

    response
.writeHead(200, {"Content-Type": "text/plain"});
    response
.write("Hello World");
    response
.end();
 
}

  http
.createServer(onRequest).listen(8888);
  console
.log("Server has started.");
}

exports
.start = start;

handlestart()  route()  

route()router.js  
function route(handle, pathname) {
  console
.log("About to route a request for " + pathname);
 
if (typeof handle[pathname] === 'function') {
    handle
[pathname]();
 
} else {
    console
.log("No request handler found for " + pathname);
 
}
}

exports
.route = route;

     handle[]();  handle    

OK    http://localhost:8888/start    :  
Server has started.
Request for /start received.
About to route a request for /start
Request handler 'start' was called.

 http://localhost:8888/    start:  
Request for / received.
About to route a request for /
Request handler 'start' was called.


 

 Hello World  server.jsonRequest()  

   onRequest    


PHPRuby  :    

 return()  onRequest  

 

   requestHandlers.js:  
function start() {
  console
.log("Request handler 'start' was called.");
 
return "Hello Start";
}

function upload() {
  console
.log("Request handler 'upload' was called.");
 
return "Hello Upload";
}

exports
.start = start;
exports
.upload = upload;

   router.js:  
function route(handle, pathname) {
  console
.log("About to route a request for " + pathname);
 
if (typeof handle[pathname] === 'function') {
   
return handle[pathname]();
 
} else {
    console
.log("No request handler found for " + pathname);
   
return "404 Not found";
 
}
}

exports
.route = route;

 

server.js:  
var http = require("http");
var url = require("url");

function start(route, handle) {
 
function onRequest(request, response) {
   
var pathname = url.parse(request.url).pathname;
    console
.log("Request for " + pathname + " received.");

    response
.writeHead(200, {"Content-Type": "text/plain"});
   
var content = route(handle, pathname)
    response
.write(content);
    response
.end();
 
}

  http
.createServer(onRequest).listen(8888);
  console
.log("Server has started.");
}

exports
.start = start;

 http://localhost:8888/start  Hello Start  http://localhost:8888/upload  Hello Upload  http://localhost:8888/foo  404 Not found  

OK    

 


     

   

start  Hello Start10  sleep()JavaScript    

requestHandlers.js:  
function start() {
  console
.log("Request handler 'start' was called.");

 
function sleep(milliSeconds) {
   
var startTime = new Date().getTime();
   
while (new Date().getTime() < startTime + milliSeconds);
 
}

  sleep
(10000);
 
return "Hello Start";
}

function upload() {
  console
.log("Request handler 'upload' was called.");
 
return "Hello Upload";
}

exports
.start = start;
exports
.upload = upload;

: start()  Node.js10Hello Startupload()    

(start()10    )  

 

 :  21  http://localhost:8888/start  URL  

2  http://localhost:8888/upload  1enter  

: 1(/start)enter  2 (/upload) enter  

:  /startURL10    /uploadURL10  sleep()  

 start()    

:  node  (In node, everything runs in parallel, except your code)    

Node.js     Node.js         

   (10)   

 probablyExpensiveFunction()()  Node.js    callbackFunction()    

(Mixu  Understanding the node.js event loop  )  

   

 

start使  (requestHandlers.js):  
var exec = require("child_process").exec;

function start() {
  console
.log("Request handler 'start' was called.");
 
var content = "empty";

  exec
("ls -lah", function (error, stdout, stderr) {
    content
= stdout;
 
});

 
return content;
}

function upload() {
  console
.log("Request handler 'upload' was called.");
 
return "Hello Upload";
}

exports
.start = start;
exports
.upload = upload;

Node.jschild_process使  便exec()  

exec()Node.js  (ls -lah")  URL/start  

 content(empty)  ls -lah"  

 http://localhost:8888/start  

Webempty    

exec()使    ()  sleep  

(ls -lah"  find /)  

   

   

exec()    

 exec()2  
function (error, stdout, stderr) {
  content
= stdout;
}

:    exec()Node.jsreturn content;  exec()exec()  contentempty  

ls -lah"()      

:  find /1  ls -lah"find /  /start URLHTTP  exec()  Node.js  exec()  find /  

   

   


使  

Node.js調  

()  HTTP  (->->)  

:    (onRequest())response    使  

 

server.js:  
var http = require("http");
var url = require("url");

function start(route, handle) {
 
function onRequest(request, response) {
   
var pathname = url.parse(request.url).pathname;
    console
.log("Request for " + pathname + " received.");

    route
(handle, pathname, response);
 
}

  http
.createServer(onRequest).listen(8888);
  console
.log("Server has started.");
}

exports
.start = start;

route()  3response  response  route  

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;

: response  

404  

requestHandlers.js:  
var exec = require("child_process").exec;

function start(response) {
  console
.log("Request handler 'start' was called.");

  exec
("ls -lah", function (error, stdout, stderr) {
    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;

 使  

startexec()  uploadHello Upload  response使  

(node index.js)  

/start  /upload  requestHandlers.js:  
var exec = require("child_process").exec;

function start(response) {
  console
.log("Request handler 'start' was called.");

  exec
("find /",
   
{ timeout: 10000, maxBuffer: 20000*1024 },
   
function (error, stdout, stderr) {
      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;

http://localhost:8888/start  HTTP10  /start  http://localhost:8888/upload    


   

       

OK  JavaScript      

 21POST  2Node.js  2  

POSTNode.js    
(POST)Node.js    使  

POST


 textarea  POST  textarea  

textareaHTML/start  requestHandler.js  
function start(response) {
  console
.log("Request handler 'start' was called.");

 
var body = '<html>'+
   
'<head>'+
   
'<meta http-equiv="Content-Type" content="text/html; '+
   
'charset=UTF-8" />'+
   
'</head>'+
   
'<body>'+
   
'<form action="/upload" method="post">'+
   
'<textarea name="text" rows="20" cols="60"></textarea>'+
   
'<input type="submit" value="Submit text" />'+
   
'</form>'+
   
'</body>'+
   
'</html>';

    response
.writeHead(200, {"Content-Type": "text/html"});
    response
.write(body);
    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;

 http://localhost:8888/start      
   

:   (  )  JavaScriptNode.js  

 /upload  POST  

 POST  使  

 POST       

 Node.jsPOST  data(POST)end()  

Node.js使  HTTPonRequestrequest  (listeners)  

:  
request.addListener("data", function(chunk) {
 
// called when a new chunk of data was received
});

request
.addListener("end", function() {
 
// called when all chunks of data have been received
});

 request   response  request  

HTTP  POST      

dataend  dataPOST  end    

server.js:  
var http = require("http");
var url = require("url");

function start(route, handle) {
 
function onRequest(request, response) {
   
var postData = "";
   
var pathname = url.parse(request.url).pathname;
    console
.log("Request for " + pathname + " received.");

    request
.setEncoding("utf8");

    request
.addListener("data", function(postDataChunk) {
      postData
+= postDataChunk;
      console
.log("Received POST data chunk '"+
      postDataChunk
+ "'.");
   
});

    request
.addListener("end", function() {
      route
(handle, pathname, response, postData);
   
});

 
}

  http
.createServer(onRequest).listen(8888);
  console
.log("Server has started.");
}

exports
.start = start;

3:  UTF-8  POSTpostDatadata  POST  end  POST  

   (POST)    

textarea  data  

 /upload  postData  router.js  
function route(handle, pathname, response, postData) {
  console
.log("About to route a request for " + pathname);
 
if (typeof handle[pathname] === 'function') {
    handle
[pathname](response, postData);
 
} 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;

requestHandler.jsupload:  
function start(response, postData) {
  console
.log("Request handler 'start' was called.");

 
var body = '<html>'+
   
'<head>'+
   
'<meta http-equiv="Content-Type" content="text/html; '+
   
'charset=UTF-8" />'+
   
'</head>'+
   
'<body>'+
   
'<form action="/upload" method="post">'+
   
'<textarea name="text" rows="20" cols="60"></textarea>'+
   
'<input type="submit" value="Submit text" />'+
   
'</form>'+
   
'</body>'+
   
'</html>';

    response
.writeHead(200, {"Content-Type": "text/html"});
    response
.write(body);
    response
.end();
}

function upload(response, postData) {
  console
.log("Request handler 'upload' was called.");
  response
.writeHead(200, {"Content-Type": "text/plain"});
  response
.write("You've sent: " + postData);
  response
.end();
}

exports
.start = start;
exports
.upload = upload;

POST  

:  POST  POSTtext  

querystring:  
var querystring = require("querystring");

function start(response, postData) {
  console
.log("Request handler 'start' was called.");

 
var body = '<html>'+
   
'<head>'+
   
'<meta http-equiv="Content-Type" content="text/html; '+
   
'charset=UTF-8" />'+
   
'</head>'+
   
'<body>'+
   
'<form action="/upload" method="post">'+
   
'<textarea name="text" rows="20" cols="60"></textarea>'+
   
'<input type="submit" value="Submit text" />'+
   
'</form>'+
   
'</body>'+
   
'</html>';

    response
.writeHead(200, {"Content-Type": "text/html"});
    response
.write(body);
    response
.end();
}

function upload(response, postData) {
  console
.log("Request handler 'upload' was called.");
  response
.writeHead(200, {"Content-Type": "text/plain"});
  response
.write("You've sent the text: "+
  querystring
.parse(postData).text);
  response
.end();
}

exports
.start = start;
exports
.upload = upload;

POST  


     

90IPO  2:  Node.js    

使Felix Geisendörfernode-formidable    POST -  使  

Felix  Node.js  Node.jsNPM  Node.js使  Node.js  
npm install formidable

 
npm info build Success: formidable@1.0.9
npm ok

 

formidable使   require:  
var formidable = require("formidable");

formidable  HTTP POSTNode.js  IncomingForm  HTTPrequest  使  

node-formidable:  
var formidable = require('formidable'),
    http
= require('http'),
    sys
= require('sys');

http
.createServer(function(req, res) {
 
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
   
// parse a file upload
   
var form = new formidable.IncomingForm();
    form
.parse(req, function(err, fields, files) {
      res
.writeHead(200, {'content-type': 'text/plain'});
      res
.write('received upload:\n\n');
      res
.end(sys.inspect({fields: fields, files: files}));
   
});
   
return;
 
}

 
// show a file upload form
  res
.writeHead(200, {'content-type': 'text/html'});
  res
.end(
   
'<form action="/upload" enctype="multipart/form-data" '+
   
'method="post">'+
   
'<input type="text" name="title"><br>'+
   
'<input type="file" name="upload" multiple="multiple"><br>'+
   
'<input type="submit" value="Upload">'+
   
'</form>'
 
);
}).listen(8888);

node    form.parsefiles:  
received upload:

{ fields: { title: 'Hello World' },
  files:
   { upload:
      { size: 1558,
        path: '/tmp/1c747974a27a6292743669e91f29350b',
        name: 'us-flag.png',
        type: 'image/png',
        lastModifiedDate: Tue, 21 Jun 2011 07:02:41 GMT,
        _writeStream: [Object],
        length: [Getter],
        filename: [Getter],
        mime: [Getter] } } }

 formidable  /tmp    

:     

Node.js  fs  

/showURL  /tmp/test.png  png  

requestHandlers.js:  
var querystring = require("querystring"),
   fs
= require("fs");

function start(response, postData) {
  console
.log("Request handler 'start' was called.");

 
var body = '<html>'+
   
'<head>'+
   
'<meta http-equiv="Content-Type" '+
   
'content="text/html; charset=UTF-8" />'+
   
'</head>'+
   
'<body>'+
   
'<form action="/upload" method="post">'+
   
'<textarea name="text" rows="20" cols="60"></textarea>'+
   
'<input type="submit" value="Submit text" />'+
   
'</form>'+
   
'</body>'+
   
'</html>';

    response
.writeHead(200, {"Content-Type": "text/html"});
    response
.write(body);
    response
.end();
}

function upload(response, postData) {
  console
.log("Request handler 'upload' was called.");
  response
.writeHead(200, {"Content-Type": "text/plain"});
  response
.write("You've sent the text: "+
  querystring
.parse(postData).text);
  response
.end();
}

function show(response, postData) {
  console
.log("Request handler 'show' was called.");
 fs
.readFile("/tmp/test.png", "binary", function(error, file) {
   
if(error) {
      response
.writeHead(500, {"Content-Type": "text/plain"});
      response
.write(error + "\n");
      response
.end();
   
} else {
      response
.writeHead(200, {"Content-Type": "image/png"});
      response
.write(file, "binary");
      response
.end();
   
}
 
});
}

exports
.start = start;
exports
.upload = upload;
exports
.show = show;

/showURLindex.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;
handle
["/show"] = requestHandlers.show;

server
.start(router.route, handle);

 http://localhost:8888/show  /tmp/test.png  

 



/startHTML  

/tmp/test.png  node-formidableupload  

/uploadURLHTML  



1multipart/form-dataHTML  textareainput  submit  requestHandlers.js:  
var querystring = require("querystring"),
   fs
= require("fs");

function start(response, postData) {
  console
.log("Request handler 'start' was called.");

 
var body = '<html>'+
   
'<head>'+
   
'<meta http-equiv="Content-Type" '+
   
'content="text/html; charset=UTF-8" />'+
   
'</head>'+
   
'<body>'+
   
'<form action="/upload" enctype="multipart/form-data" '+
   
'method="post">'+
   
'<input type="file" name="upload">'+
   
'<input type="submit" value="Upload file" />'+
   
'</form>'+
   
'</body>'+
   
'</html>';

    response
.writeHead(200, {"Content-Type": "text/html"});
    response
.write(body);
    response
.end();
}

function upload(response, postData) {
  console
.log("Request handler 'upload' was called.");
  response
.writeHead(200, {"Content-Type": "text/plain"});
  response
.write("You've sent the text: "+
  querystring
.parse(postData).text);
  response
.end();
}

function show(response, postData) {
  console
.log("Request handler 'show' was called.");
 fs
.readFile("/tmp/test.png", "binary", function(error, file) {
   
if(error) {
      response
.writeHead(500, {"Content-Type": "text/plain"});
      response
.write(error + "\n");
      response
.end();
   
} else {
      response
.writeHead(200, {"Content-Type": "image/png"});
      response
.write(file, "binary");
      response
.end();
   
}
 
});
}

exports
.start = start;
exports
.upload = upload;
exports
.show = show;

  upload  requestnode-formidableform.parse  

responsepostData  request      

postData   使:  requestdata  form.parse  (Node.js)  

server.js   postData (node-formidable)  request.setEncodingrequest:  
var http = require("http");
var url = require("url");

function start(route, handle) {
 
function onRequest(request, response) {
   
var pathname = url.parse(request.url).pathname;
    console
.log("Request for " + pathname + " received.");
    route
(handle, pathname, response, request);
 
}

  http
.createServer(onRequest).listen(8888);
  console
.log("Server has started.");
}

exports
.start = start;

router.js  postDatarequest:  
function route(handle, pathname, response, request) {
  console
.log("About to route a request for " + pathname);
 
if (typeof handle[pathname] === 'function') {
    handle
[pathname](response, request);
 
} else {
    console
.log("No request handler found for " + pathname);
    response
.writeHead(404, {"Content-Type": "text/html"});
    response
.write("404 Not found");
    response
.end();
 
}
}

exports
.route = route;

requestupload使  node-formidable/tmp  /tmp/test.png  PNG  

:  Windowsnode    

requestHandlers.js  
var querystring = require("querystring"),fs= require("fs"),
    formidable = require("formidable");

function start(response) {
  console.log("Request handler 'start' was called.");

  var body = '<html>'+
    '<head>'+
    '<meta http-equiv="Content-Type" '+
    'content="text/html; charset=UTF-8" />'+
    '</head>'+
    '<body>'+
    '<form action="/upload" enctype="multipart/form-data" '+
    'method="post">'+
    '<input type="file" name="upload" multiple="multiple">'+
    '<input type="submit" value="Upload file" />'+
    '</form>'+
    '</body>'+
    '</html>';

    response.writeHead(200, {"Content-Type": "text/html"});
    response.write(body);
    response.end();
}

function upload(response, request) {
  console.log("Request handler 'upload' was called.");

  var form = new formidable.IncomingForm();
  console.log("about to parse");
  form.parse(request, function(error, fields, files) {
    console.log("parsing done");

    /* Possible error on Windows systems:
       tried to rename to an already existing file */fs.rename(files.upload.path, "/tmp/test.png", function(err) {
      if (err) {fs.unlink("/tmp/test.png");fs.rename(files.upload.path, "/tmp/test.png");
      }
    });
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write("received image:<br/>");
    response.write("<img src='/show' />");
    response.end();
  });
}

function show(response) {
  console.log("Request handler 'show' was called.");fs.readFile("/tmp/test.png", "binary", function(error, file) {
    if(error) {
      response.writeHead(500, {"Content-Type": "text/plain"});
      response.write(error + "\n");
      response.end();
    } else {
      response.writeHead(200, {"Content-Type": "image/png"});
      response.write(file, "binary");
      response.end();
    }
  });
}

exports.start = start;
exports.upload = upload;
exports.show = show;

 PNG  Web  


 Node.jsWebJavaScript      

:     NPM  GET  

   

Node.js(  )      Node.js community wiki  the NodeCloud directory  

The perfect introduction plus the perfect reference in one bundle!

LeanBundle currently offers
the final version of
The Node Beginner Book
plus Pedro Teixeira's excellent
Hands-on Node.js for only

$9.99
(regular price $21.98)

226 pages in total
PDF, ePub & MOBI
Direct download
Free updates

Buy this
bundle now
"これはNodeの素晴らしい入門の手引きです。"
Node.jsの開発者、Ryan Dahl
"正確で的を射ていて、それでいて読んでいて楽しい。私はnodebeginner.orgが好きです。"
Specification by ExampleBridging the Communication Gapの著者、Gojko Adzic
 "Java  JavaScript  "  
Erskine、コメントより
"とてもよく書かれていて、" "あまりうまくかかれているものだから、私が一気に全部読んでしまった数少ない記事のひとつです。"
Paul Gibler、コメントより
"必須。"
@lecolibrilibre、Twitterより
"こんなに素晴らしいnode入門書を書いてくれて本当に嬉しいし、 説明が本当にわかりやすいので、書き終えてくれるのが待ち遠しいです!"
Seth McLaughlin、eメールより