温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

初学者怎么使用Node.js

发布时间:2021-11-17 15:42:52 来源:亿速云 阅读:202 作者:iii 栏目:web开发

这篇文章主要讲解了“初学者怎么使用Node.js”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“初学者怎么使用Node.js”吧!

What is Node.js?

关于Node.Js,要注意一点:Node.js本身并不是像IIS,Apache一样的webserver,它是一个JavaScript 的运行环境。当我们需要搭建一个HTTP 服务器的时候,我们可以借助Node.Js提供的库快捷的写一个。

Installing Node

Node.js 安装是非常方便的,如果你在用Windows or Mac,去这个页面就可以了download page.

I've Installed Node, now what?

以WINDOWS为例,一旦安装好Node.Js之后,可以通过两种不同方式来调用Node。

方式一:CMD 下输入node,进入交互模式,输入一行行的JS代码,Node.Js会执行并返回结果,例子:

$ node > console.log('Hello World'); Hello World undefined

PS:上一个例子的undefined来自于console.log的返回值。

方式二:CMD 下输入node 文件名(当然需要先CD到该目录)。例子:

hello.js 下的代码: console.log('Hello World'); $ node hello.js Hello World

Doing Something Useful - File I/O

使用纯粹的Js原生代码是有趣但是不利于工程开发的,Node.JS提供了一些有用的库(modules),下面是一个使用Node.js提供的库分析文件的例子:

example_log.txt 2013-08-09T13:50:33.166Z A 2 2013-08-09T13:51:33.166Z B 1 2013-08-09T13:52:33.166Z C 6 2013-08-09T13:53:33.166Z B 8 2013-08-09T13:54:33.166Z B 5

我们做的***件事情是读出该文件的所有内容。

my_parser.js  // Load the fs (filesystem) module var fs = require('fs');  // Read the contents of the file into memory. fs.readFile('example_log.txt', function (err, logData) {    // If an error occurred, throwing it will   // display the exception and end our app.   if (err) throw err;    // logData is a Buffer, convert to string.   var text = logData.toString(); });

filesystem (fs 的API ref) module 提供了一个可以异步读取文件并且结束后执行回调的函数,内容以 Buffer的形式返回(一个byte数组),我们可以调用toString() 函数,将它转换成字符串。

现在我们再来添加解析部分的代码。

my_parser.js  // Load the fs (filesystem) module. var fs = require('fs');//   // Read the contents of the file into memory. fs.readFile('example_log.txt', function (err, logData) {    // If an error occurred, throwing it will   // display the exception and kill our app.   if (err) throw err;    // logData is a Buffer, convert to string.   var text = logData.toString();    var results = {};  // Break up the file into lines.   var lines = text.split('\n');    lines.forEach(function(line) {     var parts = line.split(' ');     var letter = parts[1];     var count = parseInt(parts[2]);      if(!results[letter]) {       results[letter] = 0;     }      results[letter] += parseInt(count);   });    console.log(results);   // { A: 2, B: 14, C: 6 } });

Asynchronous Callbacks

刚才的例子中使用到了异步回调,这在Node.Js编码中是广泛被使用的,究其原因是因为Node.Js是单线程的(可以通过某些特殊手段变为多线程,但一般真的不需要这么做)。故而需要各种非阻塞式的操作。

这种非阻塞式的操作有一个非常大的优点:比起每一个请求都创建一个线程的Web Server。Node.Js在高并发的情况下,负载是小得多的。

Doing Something Useful - HTTP Server

我们来运行一个HTTP server吧, 直接复制 Node.js homepage.上的代码就可以了。

my_web_server.js      var http = require('http');      http.createServer(function (req, res) {       res.writeHead(200, {'Content-Type': 'text/plain'});       res.end('Hello World\n');     }).listen(8080);      console.log('Server running on port 8080.');

运行以上代码之后就可以访问http://localhost:8080 就能看到结果啦。

上面的例子显然过于简单,如果我们需要建立一个真正的web server。我们需要能够检查什么正在被请求,渲染合适的文件,并返回。而好消息是,Express已经做到这一点了。

Doing Something Useful - Express

Express 是一个可以简化开发的框架。我们执行npm install 来安装这个package。

$ cd /my/app/location
$ npm install express

指令执行完毕后,Express相关的文件会被放到应用目录下的node_modules文件夹中。下面是一个使用Express开发的例子:

my_static_file_server.js  var express = require('express'),     app = express();    app.use(express.static(__dirname + '/public'));  app.listen(8080);  $ node my_static_file_server.js

这样就建立了一个文件服务器。入油锅我们在 /public 文件夹放了一个"my_image.png" 。我们就可以在浏览器输入http://localhost:8080/my_image.png 来获取这个图片. 当然,Express 还提供了非常多的其它功能。

Code Organization

刚才的例子中我们使用的都是单个文件,而实际的开发中,我们会设计到代码如何组织的问题。

我们试着将最开始的文字解析程序重新组织。

parser.js  // Parser constructor. var Parser = function() {  };  // Parses the specified text. Parser.prototype.parse = function(text) {    var results = {};    // Break up the file into lines.   var lines = text.split('\n');    lines.forEach(function(line) {     var parts = line.split(' ');     var letter = parts[1];     var count = parseInt(parts[2]);      if(!results[letter]) {       results[letter] = 0;     }      results[letter] += parseInt(count);   });    return results; };  // Export the Parser constructor from this module. module.exports = Parser;

感谢各位的阅读,以上就是“初学者怎么使用Node.js”的内容了,经过本文的学习后,相信大家对初学者怎么使用Node.js这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI