Home > Web Front-end > JS Tutorial > body text

Quickly introduce you to Nodejs file operations and streams (streams)

青灯夜游
Release: 2021-08-18 10:22:48
forward
2421 people have browsed it

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.

Quickly introduce you to Nodejs file operations and streams (streams)

NodeJS file operations

  • NodeJSIn 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"]
  • 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 the fs module, which is a file module built into NodeJS. This module has many API 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('未出错')
  }
})
Copy after login
  • 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('没出错')
  }
})
Copy after login

Quickly introduce you to Nodejs file operations and streams (streams)

  • 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;
  }
})
Copy after login
  • 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 errError and stats objects, this object provides information about the file, we can judge this object information.

Quickly introduce you to Nodejs file operations and streams (streams)

Deleting files and deleting directories

  • Now that we can create using NodeJS Of course, we can also delete files, mainly using the two APIfs.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('目录已删除');
})
Copy after login
  • Both of these two 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.

Quickly introduce you to Nodejs file operations and streams (streams)

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('未出错')
  }
})
Copy after login
  • 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文件夹内了')
  }
})
Copy after login

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('追加内容')
  }
})
Copy after login
  • appendFile() can receive three parameters, the first is the path, the second is the content, and the third is the callback function, executionnode learnNode.jsThat’s it.

Quickly introduce you to Nodejs file operations and streams (streams)

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 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);
  }
})
Copy after login

Quickly introduce you to Nodejs file operations and streams (streams)

/* learnNode.js */
let fs = require('fs');
fs.readdir('./', (err, data) => {
  if(err) {
    console.log('出错');
  } else {
    console.log("读取目录成功!");
    console.log(data);
  }
})
Copy after login

Quickly introduce you to Nodejs file operations and streams (streams)

  • 可以看到我们两个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("程序执行完毕");
Copy after login
  • 我们一开始可以创建一个可读流fs.createReadStream(),参数是你要读的文件路径。
  • 当遇到了数据时会执行readerStream.on('data',callback()),如下图所示。
  • 当流结束时会执行readerStream.on('end',callback()),如下图所示。

Quickly introduce you to Nodejs file operations and streams (streams)

写入流

  • 我们上面演示了如何通过流读取一个文件,接下来我们试试通过流写入文件。
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("程序执行完毕");
Copy after login
  • 我们首先创建一个流,然后将data数据写入newJs.txt文件中。
  • 当流写入完毕时会执行readerStream.on('finish',callback()),如下图所示。

Quickly introduce you to Nodejs file operations and streams (streams)

  • 可以看到该newJs.txt文件中已经存在了我们写入的数据。

Quickly introduce you to Nodejs file operations and streams (streams)

写在最后

总的来说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!

Related labels:
source:掘金--快跑啊小卢_
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template