当前位置:网站首页>Timers, synchronous and asynchronous APIs, file system modules, file streams

Timers, synchronous and asynchronous APIs, file system modules, file streams

2022-08-10 23:40:00 Grab a child and try it

七、定时器

提供一组全局函数,可以直接调用
1、一次性定时器

开启
var timer = setTimeout(回调函数,The unit of interval time is milliseconds)
当间隔时间到了,The callback function is automatically called once,间隔时间单位为毫秒
清除
clearTimeout(timer)

//开启一次性定时器
//setTimeout(回调函数,间隔时间)
//当间隔时间到了,会自动调用回调函数
//间隔时间 单位是毫秒
var timer=setTimeout(function(){
console.log(‘boom!’)
},3000)

                                                              clearTimeout(timer)

2、周期性定时器

开启
var timer = setInterval(回调函数,间隔时间)
每隔一段时间,The callback function is automatically called once
清除
clearIntval(timer)

var timer=setInterval(function(){
console.log(‘起床了’)
},3000)

3、立即执行定时器
开启
var timer=setImmediate(回调函数)
清除
clearImmediate(timer)
开启
process.nextTick(回调函数) 只有开启,没有清除

同步执行:Execution in the main program is synchronization,It will prevent the execution of subsequent code in the main program
异步执行:The execution of the event queue after the main program is asynchronous,Subsequent code execution in the main program is not blocked

All timers are executed asynchronously

//立即执行定时器
//开启
setImmediate(function(){console.log(1)})

//执行顺序
console.log(1)
setImmediate(function(){console.log(2)})
console.log(3)
//1 3 2

//执行顺序
console.log(1)
//立即执行定时器
setImmediate(function(){console.log(2)})
//Another immediate execution timer
process.nextTick(function(){console.log(3)})
console.log(4)
//1 4 3 2

//练习:Start a periodic timer,每隔3秒钟打印‘hello’,打印3The timer is cleared after the number of times
//声明变量,用于计数
var count=0
//开启
var timer=setInterval(function(){
console.log(‘hello’)
//打印一次,记录一次
count++
//每次记录,判断,如果次数为3,则清除定时器
if (count==3)
{
clearInterval(timer)
}
},3000)

八、同步API和异步API

同步API:在主程序执行,会阻止后续代码的执行,Finally get the result through the return value
       如何解决
异步API:在一个独立的线程执行,The execution of subsequent code in the main program is not blocked,Finally, the result is obtained through the callback function

//同步API
var s=fs.statSync(‘…/02day’)
//Check if it is a file
console.log(s.isFile()) //false
//Check if it is a directory
console.log(s.isDirectory()) //true

//针对耗时的操作,采取异步API
//异步APIwill put the result in the parameter of the callback function //The main program is executed,The event queue is executed automatically,got asyncAPI结果
fs.stat(‘…/02day/06_yimer.js’,function(err,s){
//err 失败的结果
//如果有错误,就抛出错误
if (err)
{
//自定义错误
throw err //Error: ENOENT: no such file or directory
}
//s 成功的结果
console.log(s)
console.log(‘2’)
})
console.log(‘1’)
//执行顺序 1 2

九,文件系统模块( fs )

For manipulating server-side files,不是本地文件

1、Check the file status
statSyns(文件路径)/ stat(文件路径,回调函数 )
isFile() 是否为文件
isDirectory() 是否为目录

//引入系统模块
//fs是核心模块,It is the official module,go automatically toNode.jsFind it in the installation directory
const fs=require(‘fs’)
//console.log(fs)
//查看06_yimer.js文件
//Sync 同步
var s=fs.statSync(‘…/02day/06_yimer.js’)
//console.log(s)
//production to see if it is a file
console.log(s.isFile()) //true
//Check if it is a directory
console.log(s.isDirectory()) //false

var s=fs.statSync(‘…/02day’)
//Check if it is a file
console.log(s.isFile()) //false
//Check if it is a directory
console.log(s.isDirectory()) //true

2、清空写入文件
writeFileSync(文件的路径,写入的数据)/ writeFile(文件路径,写入的数据,回调函数)
如果文件不存在,先创建文件然后写入数据
如果文件存在,Clear the contents of the file first,再写入数据

const fs=require(‘fs’)
//写入文件
//往01.txt中写入用户名‘tao’
//同步
//如果文件不存在,The file will be automatically created in the same directory
//如果文件存在,The content will be cleared and then written
fs.writeFileSync(‘./1.txt’,‘tao’)

//异步
fs.writeFile(‘./2.txt’,‘楠姐’,function(err){
//err 可能产生的错误
if (err)
{
throw err
}
//A successful result is to write the data,The second parameter is no longer required
//Only successful results are a value,The second parameter is required
})

3、追加写入文件
appendFileSync(文件路径,写入数据) / appendFile(文件的路径,写入数据,回调函数)
如果文件不存在,先创建文件然后写入数据
如果文件存在,Clear the contents of the file first,再写入数据

//追加写入
//练习:Use the synchronous method to3.txt写入一个值
const fs=require(‘fs’)
fs.appendFileSync(‘3.txt’,‘我是大聪明’)
//练习:Use async methods to go4.txt写入一个值
fs.appendFile(‘4.txt’,‘Pretty girl tactics’,function(err){
if (err)
{
throw err
}
})

//练习:创建数组,Save a set of names,Loop through the array to get each name,Write the name to the filestu.txt中,使用异步方法(Observe the order of names in the file)
const fs=require(‘fs’)
var arr=[‘小王’,‘张三’,‘李四’,‘王五’,‘马哥’]
for (var i=0;i<arr.length ;i++ )
{
console.log(arr[i])
fs.appendFile(‘./stu.txt’,arr[i]+‘\n’,function(err){
if (err)
{
throw err
}
})
}
//The order of names is out of order

4、读取文件
readFileSync(文件路径)/ readFile(文件路径,回调函数)
The read format is Buffer

const fs=require(‘fs’)
var s=fs.readFileSync(‘./2.txt’)
//格式为Buffer
console.log(s.toString())

//练习:使用异步方法读取
fs.readFile(‘./2.txt’,function(err,s){
if (err)
{throw err
}
console.log(s.toString())
})
console.log(s) //<Buffer e6 a5 a0 e5 a7 90>

5、删除文件
unlinkSync(文件路径)/ unlink(文件路径,回调函数)

const fs=require(‘fs’)
var s=fs.readFileSync(‘./2.txt’)
//格式为Buffer
console.log(s.toString())
fs.readFile(‘./2.txt’,function(err,s){
if (err)
{throw err
}
console.log(s.toString())
})
console.log(s) //<Buffer e6 a5 a0 e5 a7 90>

fs.unlinkSync(‘1.txt’)

fs.unlink(‘2.txt’,(err,s)=>{
if (err)
{throw err
}
})

6、拷贝文件
copyFileSync(源文件路径,目标文件路径)/ copyFile(源文件路径,目标文件路径,回调函数)

//拷贝文件
const fs=require(‘fs’)
fs.copyFileSync(‘./4.txt’,‘./5.txt’)

十、文件流

流:A file can be divided into multiple ends
       createReadStream()     创建可读取的文件流
       createWriteStream()     创建可写入的文件流
       pipe()     管道,A read stream can be added to a write stream
       on(事件名称,回调函数)         

//引入fa文件
const fs=require(‘fs’)
//以流的方式读取文件,分为很多段
var rs=fs.createReadStream(‘./3.png’)

//Get each segment read
//添加事件:Monitors whether there is data flowing into memory
//on() Used to add events,Monitor an action
//‘data’ Fixed string form,Listen to the data stream eg,The callback function will be called automatically once it flows in

rs.on(‘data’,=>{
//参数c Indicates a piece of data read each time
console.log
})
//添加事件:Monitor whether the read is complete
//'end’是固定的字符串,监听读取结束
rs.on(‘end’,(a)=>{
console.log(‘读取结束’)
})

//打桩,See if it is synchronous or asynchronous
console.log(1) //1先执行,为异步
//引入fa文件
const fs=require(‘fs’)
//以流的方式读取文件,分为很多段
var rs=fs.createReadStream(‘./3.png’)
//创建写入流,以流的方式写入文件
var ws=fs.createWriteStream(‘./4.png’)
//Pipes the read stream to the write stream
rs.pipe(ws)

原网站

版权声明
本文为[Grab a child and try it]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208102328386824.html