node.js组成:ECMAScript+Node模块API
安装:https://nodejs.org/en/→LTS版本→默认安装;
检查是否安装成功:开始菜单→powerShell→node -v→获取版本信息;(安装成功);
=======================================================
借助命令执行工具执行:
cd ../ 上一级;
cd node 转node文件下;
文件名太长 :01.helloworld.js 解决办法 node 01+tab键(自动补全);
反复执行:↑+enter
清除:clear+enter
========================================================
在node中全局对象是:global
方法:console.log() 控制台输出
setTimeout()
clearTimeout()
setInterval()
clearInterval()
========================================================
node模块化开发:
A模块 B模块
使用exports或者module.exports(导出)
require(导入)
例子:A模块中:a.js
const add = (n1,n2) => n1+n2;
exports.add(//随便起) = add;
B模块中:b.js
const a = require('./a.js');
console.log(a);
在powershell中执行:node b.js
得到: {add:[funcition: add]}
console.log(a.add(10,20));
在powershell中执行:↑+enter;
得到:30
=========================================================
Node系统模块:
fs文件操作: const fs =require('fs');
读取文件内容:耗时(所以有回调函数)
语法:fs.reaFile('文件路径/文件名称',['文件编码'],callback);
fs.readFile('../css/base.css','utf-8',(err,doc) => {
if(err = null){
console.log(doc);
}
});
写入内容:耗时(所以有回调函数)
语法:fs.writeFile('文件路径/文件名称','数据',callback);
fs.writeFile('../index.html','content',err => {
if(err != null){
console.log(err);
return;
}
console.log('文件写入成功');
});
path路径操作
不同操作系统的路径分割不统一:windows: \ / ;linux:/;
语法:path.join('路径','路径',...);
const path = require('path');
let finialPath = path.join('itcost','y','a','m.css');
console.log(finialPath);
// itcost/y/a/m.csss
相对路径,绝对路径(相对路径在当前目录才可用,所以用绝对路径) _ _dirname
const fs =require('fs');
const path = require('path');
fs.readFile(path.join(__dirname,'01.holloworld.js'),'utf-8',(err.doc) =>{
console.log(err);
console.log(doc);
});