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 file operations
-
NodeJS
In addition to shining brightly on the Internet, it also Files can be operated. Logically speaking, as long as we use theseapi
reasonably and add some data processing, we can complete many local operations. [Recommended learning: "nodejs Tutorial"] - In the previous article we know that if you want to reference a module, you need to use
require
, The protagonist we want to introduce today is thefs
module, which is a file module built intoNodeJS
. This module has manyAPI
for us to use.
Create directories and files
- We can 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('没出错') } })
- You can see that we successfully created the directory and wrote a file.
Detecting files
- We can use
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; } })
- star() mainly receives two parameters. The first is the file to be detected, and the second is a callback function. This callback function has two parameters, namely
err
Error andstats
objects, this object provides information about the file, we can judge this object information.
Deleting files and deleting directories
- Now that we can create using
NodeJS
Of course, we can also delete files, mainly using the twoAPI
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('目录已删除'); })
- Both of these two
API
receive two parameters respectively, which are path and callback function. You can see us by executingnode learnNode.js
The file has been successfully deleted.
Rename
- We can use
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文件夹内了') } })
Append content
- We mentioned above that we can write things when creating a file, so can we directly append text to the file? Woolen cloth? We can use
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.
Reading files and reading directories
- The above are operations for adding, deleting, and modifying files. , We now also need to master the reading content. We can use
fs.readFile
andfs.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
,翻译过来就是流
的意思,提到流你会想到什么,河流,水流,都是从一个源头到另一个源头,就像水龙头从开关到流到地面,stream
也是这样一个过程。 - Stream 有四种流类型:
- Readable - 可读操作。
- Writable - 可写操作。
- Duplex - 可读可写操作.
- Transform - 操作被写入数据,然后读出结果。
- 在stream的过程中,我们也有事件可以使用,比如检测到错误触发的
error
,有数据时触发的data
。- data - 当有数据可读时触发。
- end - 没有更多的数据可读时触发。
- error - 在接收和写入过程中发生错误时触发。
- finish - 所有数据已被写入到底层系统时触发。
- 接下来简单举个例子理解一下吧。
读取流
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!

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

今天跟大家介绍一个最新开源的 javaScript 运行时:Bun.js。比 Node.js 快三倍,新 JavaScript 运行时 Bun 火了!

大家都知道 Node.js 是单线程的,却不知它也提供了多进(线)程模块来加速处理一些特殊任务,本文便带领大家了解下 Node.js 的多进(线)程,希望对大家有所帮助!

在nodejs中,lts是长期支持的意思,是“Long Time Support”的缩写;Node有奇数版本和偶数版本两条发布流程线,当一个奇数版本发布后,最近的一个偶数版本会立即进入LTS维护计划,一直持续18个月,在之后会有12个月的延长维护期,lts期间可以支持“bug fix”变更。

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools
