nodejs入门

来源:互联网 发布:jsp如何获取表单数据 编辑:程序博客网 时间:2024/05/13 12:39

Node.js是什么,这里就不再多说。经过我简单测试,执行相同的任务,Node.js(单进程)比Nginx+php快4倍,当然,这并不表示Node.js的性能就是Nginx+php的4倍,可能不同的任务场景表现各有差异。但这足以让我有兴趣去了解它了。

相关阅读:

Node.Js入门[PDF+相关代码]  http://www.linuxidc.com/Linux/2013-06/85462.htm

Node.js入门开发指南中文版 http://www.linuxidc.com/Linux/2012-11/73363.htm

Node.js可以说就是js,作为php程序员,之前接触的js完全是围绕着浏览器工作的,现在改在服务器上工作了,还有一些不适应的地方,如下:

一,自定义模块

module.js

var cfg = {"info":"Require test."};
module.exports = {
 print_hello : function() {
  return "Hello,World!";
 },
 print_info : function() {
  return cfg.info;
 }
};

main.js

var m = require("./module.js");
console.log( m.print_info() );

二,接收参数

1,get.js

var http = require("http");
var url  = require("url");
http.createServer(function(request,response) {
 var $get = url.parse(request.url,true).query;
 response.writeHead(200,{"Content-Type":"text/plain"});
 response.end($get['data']);
}).listen(1337,'192.168.9.10');
console.log("'Server running at http://192.168.9.10:1337/");

2,post.js

var http = require('http');
var querystring = require('querystring');

http.createServer(function (request, response) {
        var post_data = '';
        request.addListener('data', function(post_chunk) {
                post_data += post_chunk;
        });

        request.addListener('end', function() {
                post_data = querystring.parse(post_data);
                response.writeHead(200, {'Content-Type':'text/plain'});
                response.end(post_data.username);
        });
}).listen(1337, '192.168.9.10');
console.log("'Server running at http://192.168.9.10:1337/");

Node.js安装与配置 http://www.linuxidc.com/Linux/2013-05/84836.htm

Ubuntu 编译安装Node.js  http://www.linuxidc.com/Linux/2013-10/91321.htm

 

Node.js 的详细介绍:请点这里
Node.js 的下载地址:请点这里

三,文件读写操作

fs.js

var fs = require('fs');

// 写入文件
fs.writeFile("./message.txt", "Write file testing.\n", function (err) {
  if (err) throw err;
  console.log('It\'s saved!');
});

// 追加写入
fs.appendFile("./message.txt", "appendFile file testing.\n", function (err) {
  if (err) throw err;
  console.log('The "appendFile file testing." was appended to file!');
});

// 是否存在
fs.exists('./message.txt', function (exists) {
  console.log( exists ? "it's there" : "not exists!" );
});

// 读取文件
fs.readFile('./message.txt', function (err, data) {
        if (err) throw err;
        console.log(data.toString());
});

本篇文章来源于 Linux公社网站(www.linuxidc.com)  原文链接:http://www.linuxidc.com/Linux/2013-11/92635p2.htm


 

0 0
原创粉丝点击