Node FS - NodeJS 创建文件、读取文件、写入文件

Node FS 代表 NodeJS 文件系统模块. 在我之前的帖子中,我们已经讨论了如何使用 require() 调用来导入 Node JS 模块. 在阅读本文之前,请浏览本文[Node JS 导出和导入模块](/社区/教程/nodejs-export-and-import-modules)以了解 require() 调用。

节点 FS

在本文中,我们将讨论 Node JS 平台fs模块. FS 代表 ** 文件系统**. 此模块也被称为 IO 或 FileSystem 或 Stream 模块

NodeJS FS 模块简报

  1. 介绍 Node FS 模块
  2. Node JS 创建文件
  3. Node JS 写到文件
  4. Node JS 阅读文件

介绍Node FS模块

Node FS 模块提供了与文件系统交互的 API,并执行一些 IO 操作,如创建文件,阅读文件,删除文件,更新文件等. 像一些 Node 模块如npm,http等,Node JS fs也配备了基本的 Node JS 平台. 我们不需要做任何事情来设置 Node JS FS 模块。

Node FS 模块导入

我们只需要将节点fs模块导入我们的代码并开始写IO操作代码。

1var fs = require("fs");

这 require() 调用将 Node JS fs 模块导入缓存,并创建一个 Node FS 模块类型的对象. 一旦完成,我们可以使用 node fs 对象执行任何 IO 操作。让我们假设我们的 ${Eclipse_Workspace} 指的是 D:\RamWorkspaces\NodeWorkSpace. 现在,我将使用这个变量来参考我的 Eclipse 工作空间。 作为一个 Java 或 DOT NET 或 C/C++ 开发人员,我们已经学习并写了一些 IO 程序。 IO 或 Streams 是两种类型:

  • 写流 - 将数据写入流
  • 读流 - 读取流 的数据

Node JS 创建文件

现在我们将讨论如何使用Node JS FS API创建一个新文件。

  1. Create a Node JS Project in Eclipse IDE. Node FS Example Project
  2. Copy package.json file from previous examples and update the required things.
     1{
     2  "name": "filesystem",
     3  "version": "1.0.0",
     4  "description": "File System Example",
     5  "main": "filesystem",
     6  "author": "JournalDEV",
     7  "engines":{
     8  	"node":"*"
     9  	}
    10}
    
  3. Create a JavaScript file with the following content; fs-create-file.js
    1/**
    2 * Node FS Example
    3 * Node JS Create File
    4 */
    5var fs = require("fs");
    6
    7var createStream = fs.createWriteStream("JournalDEV.txt");
    8createStream.end();
    9```**Code Description**: `var fs = require("fs")` require() call loads specified Node FS module into cache and assign that to an object named as fs. `fs.createWriteStream(filename)` call is used to create a Write Stream and file with given filename. `createStream.end()` call ends or closes the opened stream.
    
  4. Before executing fs-create-file.js, first observe the filesystem project content and you will notice that "JournalDEV.txt" file is not available.
  5. Open command prompt at ${Eclipse_Workspace}/filesystem and run node commend to execute fs-create-file.js file as shown in below image. Node JS Create File Notice your project directory contents now, you will notice an empty file named "JournalDEV.txt".

Node JS 写到文件

我们将使用Node FS API创建一个新的文件,并将一些数据写入其中,这是我们以前的例子的延续。

  1. Remove previously created "JournalDEV.txt" from ${Eclipse_Workspace}/filesystem folder
  2. Create a Java Script file with the following content: fs-write-file.js
     1/**
     2 * Node FS Example
     3 * Node JS Write to File
     4 */
     5var fs = require("fs");
     6
     7var writeStream = fs.createWriteStream("JournalDEV.txt");
     8writeStream.write("Hi, JournalDEV Users. ");
     9writeStream.write("Thank You.");
    10writeStream.end();
    11````createStream.write(sometext)` call is used to write some text to a file.
    
  3. Open command prompt at ${Eclipse_Workspace}/filesystem and run node commend to execute fs-write-file.js file as shown below. Node JS Write to File
  4. Go to ${Eclipse_Workspace}/filesystem folder and open "JournalDEV.txt" to verify its content. Node FS Example, Node.js Write File Example Now we have created a new file and write some data into that file.

Node JS 阅读文件

我们将使用Node FS API来打开并阅读现有文件内容,并将该内容写入控制台. 这是我们以前的示例的延续。

  1. Create a Java Script file with the following content. fs-read-file1.js
     1/**
     2 * Node FS Read File
     3 * Node JS Read File
     4 */
     5var fs = require("fs");
     6
     7function readData(err, data) {
     8	  console.log(data);
     9}
    10
    11fs.readFile('JournalDEV.txt', 'utf8', readData);
    12```**Code Description**: `readData()` is a JavaScript function which takes two parameters;1. **err**: its an error object. When our program fails to open or read data from a file, then FS module writes some error message into this parameter.
    132. **data**: its a variable to hold some data.
    14This function takes data parameter and prints that data to a console. `fs.readFile()` is Node JS FS API. It takes three parameters;1. file name
    152. file data format to read
    163. A JavaScript function or JavaScript anonymous functionreadFile() reads data from a filename (first parameter) in given format (second parameter) and uses function given at third parameter to do some operation. Here we are using a plain JavaScript function as the third Parameter. We will see how to use JavaScript anonymous function in next example. In our example, readFile() reads data from "JournalDEV.txt" file and writes to console. If we dont use 'utf8' format, then we will get binary data. We will verify this in few moments.
    
  2. Open command prompt at ${Eclipse_Workspace}/filesystem and run node commend to execute fs-read-file1.js file. Node JS Read File Example Now we have observed that our code has successfully open a file, reads its content and writes its content to the console.

Node.js 读取作为二进制文件

现在我们将使用JavaScript匿名函数读取数据从一个文件。 通过这个例子来了解这一点。 它与以前的fs-read-file1.js 例子类似,但只有匿名函数。 如果您不熟悉JavaScript匿名函数,请通过一些JavaScript教程,并获得一些想法。 创建一个Java Script文件与以下内容; fs-read-file2.js

1/**
2 * Node FS File System Module
3 * Node.js read file example
4 */
5var fs = require("fs");
6
7fs.readFile('JournalDEV.txt', 'utf8', function(err, data) {
8      console.log(data);
9});

** 代码描述**:在这里 readFile() 使用 JavaScript 匿名函数读取数据从一个文件,并将该文件内容写入控制台. 当我们运行此文件时,我们将获得与 fs-read-file2.js 示例相同的输出。

1/**
2 * Node FileSystem Module  
3 * Node JS Read File Binary Data
4 */
5var fs = require("fs");
6
7fs.readFile('JournalDEV.txt', function(err, data) {
8      console.log(data);
9});

Execute above file and observe the output as shown in below image. Node.js read file as binary data Bonus TIP: To learn Node JS FS API in depth, please use Enide 2014 Studio and know all available functions and usage as shown below.

1[anyFSAPIObject] + Press . (dot) + After dot Press (CTRL + Space Bar)

Node.js FS module Enide IDE Now we are familiar with Node FS module. We are going to use this knowledge in next posts, especially in HTTP Module post. Reference: Official Documentation

Published At
Categories with 技术
Tagged with
comments powered by Disqus