Node创建服务器

不学node的前端不是好流氓。

原生搭建简单文件服务器

'use strict';

const fs = require('fs'),
    url = require('url'),
    path = require('path'),
    http = require('http');

const root = path.resolve(process.argv[2] || '.');
console.log('root' + root);

const server = http.createServer((request, response) => {
    const pathname = url.parse(request.url).pathname;
    const filepath = path.join(root, pathname);
    console.log(filepath);
    fs.stat(filepath, (err, stats) => {
        if (pathname === '/') {
            const indexPath = path.join(root, 'index.html');
            const defaultPath = path.join(root, 'default.html');
            fs.stat(indexPath, function (err, stat) {
                if (err) {
                    fs.stat(defaultPath, function (err, stat) {
                        if (err) {
                            console.log('can\'t find flie!');
                            response.writeHead(404, { 'Content-Type': 'text/html' });
                            response.end('<p>404 Not Found</p>')
                        } else {
                            console.log('file is exist!');
                            response.writeHead(200);
                            fs.createReadStream(defaultPath).pipe(response);
                        }
                    });
                } else {
                    console.log('file is exist!');
                    response.writeHead(200);
                    fs.createReadStream(indexPath).pipe(response);
                }
            });
        } else {
            if (!err && stats.isFile()) {
                console.log(`200 ${request.url}`);
                response.writeHead(200);
                fs.createReadStream(filepath).pipe(response);
            } else {
                console.log(`404 ${request.url}`);
                response.writeHead(404);
                response.end('404 Not Found');
            }
        }
    })

});

server.listen(8090);
console.log('server is running at http://127.0.0.1:8090/');

代码分析

  • path.resolve([...paths])

path.resolve([...paths])#
Added in: v0.3.4
...paths: <String> A sequence of paths or path segments
Returns: <String>

The path.resolve() method resolves a sequence of paths or path segments into an absolute path.
The given sequence of paths is processed from right to left, with each subsequent path
prepended until an absolute path is constructed. For instance, given the sequence of path segments: /foo, /bar, baz,** calling path.resolve('/foo', '/bar', 'baz')** would <b>return /bar/baz </b>.
If after processing all given path segments an absolute path has not yet been generated, the current working directory is used.
The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.
Zero-length path segments are ignored.
If no path segments are passed, path.resolve() will return the absolute path of the current working directory.
For example:

path.resolve('/foo/bar', './baz');  // Returns: '/foo/bar/baz';
path.resolve('/foo/bar', '/tmp/file/'); // Returns: '/tmp/file';
path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
// if the current working directory is /home/myself/node;
// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'

A TypeError
is thrown if any of the arguments is not a string.
通过官方文档可知 path.resolve()是用来解析合成绝对路径的。

  • process.argv

Added in: v0.1.27
<Array>

The process.argv property returns an array containing the command line arguments passed when the Node.js process was launched. The first element will be process.execPath. See process.argv0 if access to the original value of argv[0] is needed. The second element will be the path to the JavaScript file being executed. The remaining elements will be any additional command line arguments.
For example, assuming the following script for process-args.js:

// print process.argv
process.argv.forEach((val, index) => {
  console.log(`${index}: ${val}`);
});

Launching the Node.js process as:

$ node process-2.js one two=three four

Would generate the output:

0: /usr/local/bin/node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four

总结: 这个是返回一个数组,第一个元素是node的执行文件目录** 的路径,第二个元素是js执行文件** 的路径,剩下的元素可以是任何 命令行 的参数。

  • http.createServer([requestListener])#

Added in: v0.1.13
Returns: <http.Server>

Returns a new instance of http.Server.
The requestListener is a function which is automatically added to the 'request'
event.

  • server.listen([port][, hostname][, backlog][, callback])#

Added in: v0.1.90
port <Number>
hostname <String>
backlog <Number>
callback <Function>

Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections on any IPv6 address (::) when IPv6 is available, or any IPv4 address (0.0.0.0) otherwise. Omit the port argument, or use a port value of 0, to have the operating system assign a random port, which can be retrieved by using server.address().port after the 'listening' event has been emitted.
To listen to a unix socket, supply a filename instead of port and hostname.
backlog is the maximum length of the queue of pending connections. The actual length will be determined by your OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on linux. The default value of this parameter is 511 (not 512). This function is asynchronous. callback will be added as a listener for the 'listening' event. See also net.Server.listen(port).
Note: The server.listen() method may be called multiple times. Each subsequent call will re-open the server using the provided options.
总结:这就是用来监听端口的。奇怪的是如果端口为0或者没传,操作系统会随机分配一个端口。

  • url.parse(urlString[, parseQueryString[, slashesDenoteHost]])#

Added in: v0.1.25
urlString <String> The URL string to parse.
parseQueryString <Boolean> If true, the query property will always be set to an object returned by the querystring module's parse() method. If false, the query property on the returned URL object will be an unparsed, undecoded string. Defaults to false.
slashesDenoteHost <Boolean> If true, the first token after the literal string // and preceding the next / will be interpreted as the host. For instance, given //foo/bar, the result would be {host: 'foo', pathname: '/bar'} rather than {pathname: '//foo/bar'}. Defaults to false.
The url.parse() method takes a URL string, parses it, and returns a URL object.
这个是用来解析URL字符串的,解析成 URLobject.

  • path.join([...paths])

Added in: v0.1.16
...paths <String> A sequence of path segments
Returns: <String>
For example:

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
// Returns: '/foo/bar/baz/asdf'

path.join('foo', {}, 'bar')
// throws TypeError: Arguments to path.join must be strings

总结:这是用来合成路径的。

  • fs.stat(path, callback)

Added in: v0.0.2
path<String> | <Buffer>
callback <Function>
总结: 它返回一个Stat对象,能告诉我们文件或目录的详细信息

  • fs.createReadStream(path[, options])

总结: 打开创建一个可读流。

  • fs.createWriteStream(path[, options])

总结: 打开创建一个可写流。所有可以读取数据的流都继承自stream.Readable,所有可以写入的流都继承自stream.Writable。

  • pipe()

一个Readable流和一个Writable流串起来后,所有的数据自动从Readable流进入Writable流,这种操作叫pipe。

总结

这是原生node搭建的一个文件读取服务器,基本读取功能齐全,能做静态网页(简单的官网等)的应用,代码不是很难,稍微了解node的人都能很好的理解。重点是了解和熟悉node API 和 编程思想,为以后真正应用做基础。 在命令行运行 ** node xxx.js(服务器js) /path/to/dir**,把 **/path/to/dir **改成你本地的一个有效的目录。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容