search
HomeWeb Front-endJS TutorialQuickly introduce you to Nodejs file operations and streams (streams)

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

Aug 18, 2021 am 10:22 AM
nodejsstreamFile operationsflow

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('未出错')
  }
})
  • 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('没出错')
  }
})

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;
  }
})
  • 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('目录已删除');
})
  • 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('未出错')
  }
})
  • 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.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);
  }
})

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);
  }
})

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("程序执行完毕");
  • 我们一开始可以创建一个可读流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("程序执行完毕");
  • 我们首先创建一个流,然后将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!

Statement
This article is reproduced at:掘金--快跑啊小卢_. If there is any infringement, please contact admin@php.cn delete
JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools