Node.js 教程是 Node.js 的入门教程。我们描述了 Node.js 并提供了一些 Node.js 代码示例。
Nojde.js
Node.js 是一个开源、跨平台的 JavaScript 运行时环境。它建立在 Chrome 的 V8 JavaScript 引擎之上。 Node.js 使用事件驱动的非阻塞 I/O 模型,使其轻量级且高效。Node.js 最初由 Ryan Dahl 于 2009 年编写。
Node.js 提供了丰富的各种 JavaScript 模块库,例如用于处理文件系统的fs
或用于处理 HTTP 请求和响应的http
。
Node.js 应用程序是用 JavaScript 编写的,可以在 OS X、Microsoft Windows 和 Linux 上的 Node.js 运行时中运行。
Node.js 有一个名为npm
的包管理器,它是一个巨大的开源 JavaScript 库生态系统。
Node.js安装
我们安装了最新版本的 Node.js。按照适用于您的平台的 Node.js 网站上的安装说明进行操作。
Node.js 第一个例子
我们创建一个简单的控制台应用程序。
console.log("This is our first application");
程序向控制台打印一条消息。
$ node first.js This is our first application
Node.js 读取文件内容
Node.js 包含用于处理文件的fs
模块。
blue book pen dog computer screen
我们有一个文本文件。
Node.js 中的大多数函数都是异步的。它们是非阻塞的;即它们不会阻止脚本的执行。
const fs = require('fs') fs.readFile('words.txt', 'utf-8', (err, data) => { if (err) throw err; console.log(data); }); console.log("Script continues...")
该示例读取words.txt
文件的内容。
const fs = require('fs');
我们加载fs
模块。
fs.readFile('words.txt', 'utf-8', (err, data) => {
readFile
异步读取文件的全部内容。我们在方法的第二个参数中指定编码。
$ node read_file.js Script continues blue book pen dog computer screen
“脚本继续”显示在文件内容之前。
Node.js同步读取目录
现在我们要读取一个目录的内容。
const fs = require('fs'); readDirContentSync('.'); console.log("Ready."); function readDirContentSync(mydir) { const filenames = fs.readdirSync(mydir); for (var i = 0; i < filenames.length; i++) { console.log(filenames[i]); } }
代码示例同步读取目录的内容。
const filenames = fs.readdirSync(mydir);
我们用readdirSync
同步读取目录。
for (var i = 0; i < filenames.length; i++) { console.log(filenames[i]); }
我们遍历文件名数组并将它们打印到控制台。
$ node readdir_syn.js builtins.js first.js links read_file.js readdir_asyn.js readdir_syn.js server.js todo words.txt Ready.
通过同步函数调用,“准备就绪”。消息在函数完成执行后显示。
Node.js 异步读取目录
在下一个示例中,我们异步读取目录。
var fs = require('fs'); fs.readdir(".", (err, filenames) => { for (var i = 0; i < filenames.length; i++) { console.log(filenames[i]); } console.log("Ready."); });
readdir
异步读取当前工作目录的内容。它用目录中不包括“.”的文件名填充一个数组。和“..”。
Node.js读取网页
在下面的示例中,我们使用内置的http
模块读取网页。
const http = require('http'); const request = http.request({ hostname: 'webcode.me' }, (res) => { res.setEncoding('utf8'); res.on('data', (chunk) => { console.log(chunk); }); }); request.end(); request.on('error', (err) => { console.log("Error occured\n"); console.error(err); });
在示例中,我们使用http
模块创建对一个小网页的请求。返回的 HTML 页面被打印到控制台。
$ node read_webpage.js <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My html page</title> </head> <body> <p> Today is a beautiful day. We go swimming and fishing. </p> <p> Hello there. How are you? </p> </body> </html>
我们收到了这个小的 HTML 页面。
Node.js 使用 npm 安装模块
可以使用npm
Node PackageManager 安装其他模块。现在我们要安装一个名为builtin-modules
的新模块。在这个模块中,我们将列出所有可用的 Node.js 内置模块。
$ mkdir builtmodtest $ cd builtmodtest/ $ npm init
我们创建一个新的项目目录。使用 npm init
命令我们创建一个 package.json
文件。它包含与项目相关的元数据,例如应用程序名称、作者或依赖项。
$ cat package.json { "name": "builtmodtest", "version": "1.0.0", "description": "Testing builtin modules", "main": "main.js", "scripts": { "start": "node main.js" }, "author": "Jan Bodnar", "license": "ISC" }
这是初始package.json
文件。我们选择main.js
作为主文件。
$ npm install builtin-modules $ tree -L 1 . âââ main.js âââ node_modules âââ package.json âââ package-lock.json
使用npm install builtin-modules
我们在本地安装builtin-modules
模块。将创建一个新的node_modules
目录,其中存储模块及其依赖项。 package-lock.json
文件由 npm 自动创建。它用于确保团队成员、部署和持续集成的依赖项安装一致。此文件必须提交到源存储库。
$ cat package.json { "name": "builtmodtest", "version": "1.0.0", "description": "Testing builtin modules", "main": "main.js", "scripts": { "start": "node main.js" }, "author": "Jan Bodnar", "license": "ISC", "dependencies": { "builtin-modules": "^2.0.0" } }
builtin-modules
也写入了package.json
文件。
const builtmods = require('builtin-modules'); console.log(builtmods);
这是main.js
文件。它将所有内置模块打印到控制台。
$ npm start > builtmod@1.0.0 start /home/janbodnar/prog/nodejs/builtmod > node main.js [ 'assert', 'async_hooks', 'buffer', 'child_process', 'cluster', 'config', 'console', 'constants', ... ]
Node.js 服务器
我们使用 Node.js http
模块创建一个简单的服务器。
const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {"Content-Type": "text/plain"}); res.end("Hello there\n"); }); server.listen(8000); console.log("Server running at http://127.0.0.1:8000/");
服务器向客户端发送一条简单的文本消息。
const http = require('http');
我们加载http
模块来创建一个http服务器。
const server = http.createServer((req, res) => { res.writeHead(200, {"Content-Type": "text/plain"}); res.end("Hello there\n"); });
服务器已创建。它向客户端发送一条文本消息。
server.listen(8000);
服务器侦听本地主机上的端口 8000。
$ node server.js & $ curl localhost:8000 Hello there
我们运行服务器并使用curl
创建请求。
在本文中,我们介绍了 Node.js。我们已经使用 Node.js 创建了一些代码示例。
列出 JavaScript 教程。