Node.js学习笔记——内置模块

Node.js内置模块

  • 1.Path 模块
  • 2.file system模块
    • 阻塞代码实例:
    • 非阻塞代码实例:

在 Node.js 模块库中有很多好用的模块。
下面基于我的项目结构为:
Node.js学习笔记——内置模块_第1张图片

1.Path 模块

提供了处理和转换文件路径的工具。
path模块提供了parse方法:将完整路径中各个部分解析出来。root是当前模块根路径,dir是当前模块的文件夹位置,base是模块名字,ext是模块后缀

const path = require("path");
console.log(path.parse(__filename));

//控制端显示
{
  root: 'D:\\',
  dir: 'D:\\vscode project\\test',
  base: 'module_path.js',
  ext: '.js',
  name: 'module_path'
}

2.file system模块

文件操作系统,提供了和操作文件相关的方法
操作如下:

//同步方法
const fs = require("fs");
const u = fs.readdirSync("./");          
console.log(u);

//异步方法
const fs = require("fs");
fs.readdir("./", function (error, files) {   //异步方法
  console.log(files);
});

执行显示:
Node.js学习笔记——内置模块_第2张图片

阻塞代码实例:

input.txt的内容是:

加油,你马上就要成功了!!!

main.js的代码片段如下:

var fs = require("fs");
var data = fs.readFileSync("input.txt");
console.log(data.toString());
console.log("over!!!");

执行情况:
在这里插入图片描述

非阻塞代码实例:

main.js的代码片段如下:

var fs = require("fs");
fs.readFile("input.txt", function (error, data) {
  if (error) return console.log(error);
  console.log(data.toString());
});
console.log("over!!!");

执行情况:
在这里插入图片描述
可以看出非堵塞代码不需要等待文件读取完,这样就可以在读取文件时同时执行接下来的代码,大大提高了程序的性能。

你可能感兴趣的:(前端学习路径,node.js,前端,javascript)