Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine.
与JavaScript的区别:
node.js可以干什么?
eg:爬虫爬取豆瓣电影内容
const puppeteer = require('puppeteer');
const url = 'https://movie.douban.com/subject/26794435';
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url);
const film = await page.evaluate(() => {
const title = $('h1 > span:first-child').text();
const poster = $('#mainpic img').attr('src');
const desc = $('span[property="v:summary"]').text().trim();
return {
title, poster, desc};
});
console.log(JSON.stringify(film, null, ' '));
await browser.close();
})();
eg:Hello World:
// index.js
console.log('Hello World');
Hello World
➜ ~ node index.js
Hello World
eg:读写文件:
const fs = require('fs');
fs.readFile('test.txt', (err, data) => {
console.log(data);
});
console.log('read file content');
const fs = require('fs');
fs.readFile('a.text', (err, buffer) => {
console.log(buffer);
})
const {
readFile} = require('fs');
readFile('a.txt', (err, buffer) => {
console.log(buffer);
})
// app.js
var circle = require('./circle.js');
console.log('半径为4的圆面积是:' + circle.area(4));
// circle.js
const pi = Math.PI;
exports.area = function (r) {
return pi * r * r;
};
exports.circumference = function (r) {
return 2 * pi * r;
};
// 加载绝对路径文件
require('/foo/bar/a.js');
// 加载相对路径文件
require('../a.js');
// 加载无后缀的文件
require('../a');
// 加载外部模块
require('pkg-name');
// app.js
const circle = require('./circle.js');
require 并不是全局变量
定义的变量 circle 会污染其他文件么?(不会,在闭包内进行require,circle的上下文会在闭包里)
执行步骤:
(function (exports, require, module, __filename, __dirname) {
var circle = require('./circle.js');
console.log('The area is ' + circle.area(4));
});
➜ star-plan npm init -y //快速创建package.json文件
Wrote to /Users/lizheming/star-plan/package.json:
{
"name": "star-plan",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Tip: 可以使用 npm config set init.author.name
等命令修改初始化时的默认值
重要的meta信息:
包依赖示例:
"dependencies": {
"accepts": "^1.2.2",//允许中版本和小版本更新
"content-disposition": "~0.5.0",//接受小版本更新
"cookies": "~0.7.0",
"debug": "*",//接受任意版本更新
"delegates": "^1.0.0",
"escape-html": "~1.0.1",
"fresh": "^0.5.2",
"only": "0.0.2",//只安装该版本
"parseurl": "^1.3.0",
"statuses": "^1.2.0",
"type-is": "^1.5.5",
"vary": "^1.0.0"
},
包依赖的多种写法:
1.0.0 Must match version exactly
>1.0.0 Must be greater than version
>=1.0.0 <1.0.0 <=1.0.0
~1.0.0 "Approximately equivalent to version"
^1.0.0 "Compatible with version"
1.2.x 1.2.0, 1.2.1, etc., but not 1.3.0
* Matches any version
version1 - version2 Same as >=version1 <=version2.
...