---
title: "nodejs使用（2）一个文件服务器"
author: "hanyh"
date: "2010-10-22T10:08:14Z"
tags: ["浏览器"]
categories: ["非技术"]
slug: "nodejs-2"
draft: false
lastmod: "2010-10-22T10:08:14Z"
id: 791200
url: "https://hanyh.iteye.com/blog/791200"
---

注意nodejs现在还不是稳定版本，api命名会不停变化，如writeHead，以前就叫作sendHeader...

process.cwd()服务器当前进程路径

测试，访问：http://localhost:8080/fileserver.js
可以看到浏览器把内容输出



fileserver.js

```js


var sys = require("sys"),  
    http = require("http"),  
    url = require("url"),  
    path = require("path"),  
    fs = require("fs");  
  
http.createServer(function(request, response) {  
    var uri = url.parse(request.url).pathname;  
   
    var filename = path.join(process.cwd(), uri);  
    sys.puts(filename)
    path.exists(filename, function(exists) {  
        if(!exists) {  
            response.writeHead(404, {"Content-Type": "text/plain"});  
            response.write("404 Not Found\n");  
            response.end();  
            return;  
        }  
  
        fs.readFile(filename, "binary", function(err, file) {  
            if(err) {  
                response.writeHead(500, {"Content-Type": "text/plain"});  
                response.write(err + "\n");  
                response.end();  
                return;  
            }  
  
            response.writeHead(200);  
            response.write(file, "binary");  
            response.end();  
        });  
    });  
}).listen(8080);  
  
sys.puts("Server running at http://localhost:8080/")


```

从中学习：
1，引入包
require(module)
2,request, response对象：
This object is created internally by a HTTP server--not by the user--and passed as  argument to listener.
....
直接查看API文档吧:)说得相当直接