Home >Web Front-end >JS Tutorial >Quickly introduce you to Nodejs file operations and streams (streams)
This article will introduce to you the file operations in Nodejs (create and delete directories/files, rename, append content, read content), and briefly talk about streams.
NodeJS
In addition to shining brightly on the Internet, it also Files can be operated. Logically speaking, as long as we use these api
reasonably and add some data processing, we can complete many local operations. [Recommended learning: "nodejs Tutorial"]require
, The protagonist we want to introduce today is the fs
module, which is a file module built into NodeJS
. This module has many API
for us to use. fs.mkdir
fs.writeFile
to Create directories and files separately. mkdir()
can receive three parameters, the first is the path, the second is an optional option representing permissions, we generally do not need this, the third parameter is a callback function , we can do some processing here. /* learnNode.js */ let fs = require('fs'); fs.mkdir('js',(err)=>{ if(err){ console.log('出错') }else{ console.log('未出错') } })
writeFile()
can receive four parameters, the first is the path, the second is the file content, the third option represents permissions, and the third Four are callback functions. /* learnNode.js */ let fs = require('fs'); fs.writeFile('./js/newJs.js','console.log("写入这个")',(err)=>{ if(err){ console.log('出错') }else{ console.log('没出错') } })
fs.stat
to detect whether a file in a path is a directory or a file. Then you can do some operations. /* learnNode.js */ let fs = require('fs'); fs.stat('./js/newJs.js', (error, stats) => { if(error) { console.log(error); return false; } else { console.log(`是否文件:${stats.isFile()}`); console.log(`是否目录:${stats.isDirectory()}`); return false; } })
err
Error and stats
objects, this object provides information about the file, we can judge this object information. NodeJS
Of course, we can also delete files, mainly using the two API
fs.unlink``fs.rmdir
. /* learnNode.js */ let fs = require('fs'); fs.unlink('./js/newJs.js', (err) => { if (err) throw err; console.log('文件已删除'); }); fs.rmdir('./js',(err)=>{ if (err) throw err; console.log('目录已删除'); })
API
receive two parameters respectively, which are path and callback function. You can see us by executing node learnNode.js
The file has been successfully deleted. fs.rename
to rename the file Rename. /* learnNode.js */ let fs = require('fs'); fs.rename('oldJs.js','newJs.js',(err)=>{ if(err){ console.log('出错') }else{ console.log('未出错') } })
rename()
can receive three parameters. The first is the path, the second is the changed name, and the third is the callback function. It is worth noting Yes, if the location of the file corresponding to the first parameter and the second parameter is different, it will not rename the previous file but directly cut the file and place it in another location. /* learnNode.js */ let fs = require('fs'); fs.rename('newJs.js','./js/oldJs.js',(err)=>{ if(err){ console.log('出错') }else{ console.log('剪切到js文件夹内了') } })
fs.appendFile
. /* learnNode.js */ let fs = require('fs'); fs.appendFile('newJs.txt','我是追加的内容',(err)=>{ if(err){ console.log('出错') }else{ console.log('追加内容') } })
appendFile()
can receive three parameters, the first is the path, the second is the content, and the third is the callback function, executionnode learnNode.js
That’s it. fs.readFile
and fs.readdir
to read files and read directories respectively. /* learnNode.js */ let fs = require('fs'); fs.readFile('newJs.txt', (err, data) => { if(err) { console.log('出错'); } else { console.log("读取文件成功!"); console.log(data); } })
/* learnNode.js */ let fs = require('fs'); fs.readdir('./', (err, data) => { if(err) { console.log('出错'); } else { console.log("读取目录成功!"); console.log(data); } })
API
都是接收两个参数,第一个是路径,第二个是回调函数,这个回调函数也有两个参数里面包含了data
信息,我们可以打印这个data
信息来获取内容。stream
,翻译过来就是流
的意思,提到流你会想到什么,河流,水流,都是从一个源头到另一个源头,就像水龙头从开关到流到地面,stream
也是这样一个过程。error
,有数据时触发的data
。var fs = require("fs"); var data = ''; // 创建可读流 var readerStream = fs.createReadStream('newJs.txt'); // 设置编码为 utf8。 readerStream.setEncoding('UTF8'); // 处理流事件 遇到有数据时执行这个 readerStream.on('data', function(chunk) { data += chunk; console.log(chunk,'流遇到数据了') }); // 处理流事件 流结束时执行这个 readerStream.on('end',function(){ console.log(data,'流结束了'); }); // 处理流事件 流报错时执行这个 readerStream.on('error', function(err){ console.log(err.stack); }); console.log("程序执行完毕");
fs.createReadStream()
,参数是你要读的文件路径。readerStream.on('data',callback())
,如下图所示。readerStream.on('end',callback())
,如下图所示。var fs = require("fs"); var data = '我是小卢,我再写入流'; // 创建一个可以写入的流,写入到文件 newJs.txt 中 var writerStream = fs.createWriteStream('newJs.txt'); // 使用 utf8 编码写入数据 writerStream.write(data,'UTF8'); // 标记文件末尾 writerStream.end(); // 处理流事件 完成和报错时执行 writerStream.on('finish', function() { console.log("写入完毕"); }); writerStream.on('error', function(err){ console.log(err.stack); }); console.log("程序执行完毕");
data
数据写入newJs.txt
文件中。readerStream.on('finish',callback())
,如下图所示。newJs.txt
文件中已经存在了我们写入的数据。总的来说NodeJS
提供了fs
文件操作模块,这个模块有很多的API
,上面只是简单的展示了一下,还有很多有趣的API
大家只需要用到的时候去官网查就好了,因为NodeJS
能操作文件,小至文件查找,大至代码编译。换个角度讲,几乎也只需要一些数据处理逻辑,再加上一些文件操作,就能够编写出大多数前端工具。
原文地址:https://juejin.cn/post/6997204352683212831
作者:快跑啊小卢_
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of Quickly introduce you to Nodejs file operations and streams (streams). For more information, please follow other related articles on the PHP Chinese website!