📜  Node.js 中的文件系统模块是什么?

📅  最后修改于: 2022-05-13 01:56:33.600000             🧑  作者: Mango

Node.js 中的文件系统模块是什么?

Nodejs 是一个开源的 javascript 运行时,用于在浏览器之外运行 javascript。它是后端开发的流行选择。像其他所有编程语言一样,Nodejs 也为我们提供了与系统或机器交互的内置库。在 Nodejs 中,我们将这些库称为模块。

模块基本上分为3类:

  1. 节点核心模块
  2. 本地模块
  3. 3rd 方模块(如 npm 模块)。

文件系统模块:文件系统是一个由节点与文件和文件夹交互的核心模块。它提供了各种事件和方法来访问和操作我们机器中的文件和文件夹。

它提供的一些操作文件的操作是:

  • 创建和删除文件或文件夹。
  • 访问和重命名文件或文件夹。
  • 读取、写入和附加文件。
  • 更改文件或文件夹的权限和所有者。

要在您的程序中使用文件系统模块,您需要 fs 节点核心模块:

句法:

const fs = require('fs')

现在在使用 fs 模块之前,您需要了解使用 fs 模块方法有两种方法:-

  1. 使用同步方法
  2. 使用异步方法

现在问题来了,我们应该选择同步方法还是异步方法。下面我们来讨论一下 fs 模块的同步方法和异步方法有什么区别。

同步和异步方法:

同步方法使用本质上是阻塞的函数。阻塞函数会阻塞下一条指令或一段代码的执行,直到当前操作未完成。同步方法等待当前操作完成,然后继续执行下一条指令。但是当当前操作花费大量时间时,这会产生问题。

示例:假设我们的服务器收到请求后需要创建一个文件,然后在其中写入一些文本,然后响应客户端。如果为了创建和写入文件,我们使用同步方法,那么对于每个即将到来的请求,我们将阻止执行,直到我们完成操作并响应该客户端。如果很多请求聚集在一起,我们基本上会阻止其他用户,直到我们完成第一个用户。最后一个用户必须等待很长时间才能获得此响应,这很糟糕。

异步方法本质上是非阻塞的,因为它们从不等待当前操作完成。在调用异步方法时,我们必须将回调函数作为参数传递。当一个异步函数被调用时,它被事件循环注册或推送到一个队列并执行下一行代码。在后台,我们的异步函数被执行,当它完成时,我们作为参数传递的回调函数被推送到回调队列中,并在轮到它时执行。

Basically, the catch here is to understand that asynchronous methods do the operation in the background and do not block the 
 execution of code.

同步和异步代码执行

文件系统为我们提供了同步和异步版本的方法。

注意如果可以选择,我们应该始终在代码中使用异步版本的方法。同步方法应该只用在顶层代码中,因为顶层代码只执行一次,或者只在我们确定操作不会花费很长时间的情况下(轻量级操作)。

档案操作:

  • 读取文件——读取文件最简单的方法是使用fs.readFile()方法。此方法负责打开和关闭文件,并将文件内容加载到内存中供我们在程序中使用。

句法 :

fs.readFile(path,options,callback);

参数 :

  • path – 我们要读取的文件的名称或路径
  • options - 这是一个可选参数,通常我们传递编码是 ' utf-8 '
  • 回调——当我们读取文件时执行。它需要两个参数
    • error – 如果发生任何错误
    • 数据——文件的内容

示例 –创建一个文件名app.js并创建一个文本文件input.txt

项目结构——

app.js
const fs = require("fs");
// Asynchronous version of readFile method
fs.readFile("input.txt", "utf-8", (error, data) => {
  
  // If the file doesnt exist then there 
  // is error then if condition will run
  if (error) {
    console.log("File not found");
  } else {
  
    // Data contains the content that we 
    // have read from file in case of 
    // error , data will output undefined
    console.log(data);
  }
});


Javascript
const fs = require("fs");
  
try {
  // If file not found then throws error
  //Reading file in asynchronous way
  const data = fs.readFileSync("input.txt", "utf-8");
  console.log(data);
} catch (error) {
  console.log(error);
}


app.js
const fs = require("fs");
  
const str = "Learning how to write to a file.";
  
fs.writeFile("output.txt", str, "utf-8", (error) => {
  
  // If there is error then this will execute
  if (error) {
    console.log(error);
  }
  else {
    console.log("Successfully written!!");
  }
    
  // Reading what we have written in file
  fs.readFile("output.txt", "utf-8", (error, data) => {
    if (error) {
      console.log(error);
    } 
    else {
      console.log(data);
    }
  });
});


Javascript
const fs = require("fs");
  
const data = "\nLearning how to append to a file. (New content)";
fs.appendFile("output.txt", data, "utf-8", (error) => {
  if (error) {
    console.log(error);
  } 
  else {
    console.log("Successfully written!!");
  }
  
  fs.readFile("output.txt", "utf-8", (error, data) => {
    if (error) {
      console.log(error);
    }
    else {
      console.log(data);
    }
  });
});


Javascript
// Complete this function to find the 
// absolute difference of sum of even 
// and odd terms in arr
function diffOfOddEvenSum(arr) {
  
  // Write your code here
}


app.js
const fs = require("fs");
const funct = require("./index");
function diffOfOddEvenSum(arr) {
  let odd = 0;
  let even = 0;
  
  arr.forEach((element) => {
    
    if (element % 2 == 1) {
      odd += element;
    } else even += element;
  });
  
  return odd - even;
}
  
// OFFLINE-JUDGE
// Since this is top level code we can
// use Synchronous version
// reading the data from json file
const jsonData = fs.readFileSync("test.json", "utf-8");
  
// The data we read from file is in json
// parsing the json to get the data
const testCases = JSON.parse(jsonData);
  
// Inputs is an array of input cases
const inputs = testCases.input;
  
// Exptected Output contains the correct
// output of the given problem number
const expectedOutput = testCases.output;
  
// To store the result of our input test cases
let result = "";
  
// Calling the diffOdOddEvenSum() function
// to get the output
inputs.forEach((input, index) => {
  const output = diffOfOddEvenSum(input);
  //  console.log(output)
  
  // Checking if the output is correct
  if (output == expectedOutput[index]) {
    result += `Test Case ${index + 1}- passed \n`;
  } else {
    result += `Test Case ${index + 1}- failed \n`;
  }
});
  
// We can use Synchronous version as it
// is top-level code
// writing the output to the file
fs.writeFileSync("result.txt", result, "utf-8");


使用以下命令运行app.js

node app.js

输出:

Hurrah, now you know how to read a file.

示例 2:我们将使用同步版本,即fs.readFileSync() 。下面讨论的所有其他方法也有一个同步版本。要使用它,只需在函数名称的末尾添加 Sync 并删除回调参数。

Javascript

const fs = require("fs");
  
try {
  // If file not found then throws error
  //Reading file in asynchronous way
  const data = fs.readFileSync("input.txt", "utf-8");
  console.log(data);
} catch (error) {
  console.log(error);
}

输出 :

Hurrah, now you know how to read a file synchronously.
  • 写入文件——我们可以使用fs.writeFile()函数写入文件。此函数通过替换文件的现有内容将数据写入文件。此外,如果没有这样的文件,那么它会创建该文件并在其上写入数据。

句法:

fs.writeFile(path, data, options, callback)

参数:

  • path – 要写入的文件的名称或路径。
  • data - 写入文件的内容
  • options - 可选,但我们通常指定编码 - ' utf-8 '。
  • 回调——在我们写入文件后执行。
    • 错误——如果发生任何错误,

示例– 创建一个空文本文件 – output.txtapp.js文件 –

项目结构:

应用程序.js

const fs = require("fs");
  
const str = "Learning how to write to a file.";
  
fs.writeFile("output.txt", str, "utf-8", (error) => {
  
  // If there is error then this will execute
  if (error) {
    console.log(error);
  }
  else {
    console.log("Successfully written!!");
  }
    
  // Reading what we have written in file
  fs.readFile("output.txt", "utf-8", (error, data) => {
    if (error) {
      console.log(error);
    } 
    else {
      console.log(data);
    }
  });
});

使用命令运行app.js文件 –

node app.js

输出:将创建一个名为output.txt的新文件,并在其上写入数据。但是文件已经存在,那么它的所有内容都将被删除并替换为我们写入的数据。

Successfully written!!
Learning how to write to a file.
  • 附加到文件中——我们可以使用将数据附加到我们的文件中 fs.appendFile() 。与fs.writeFile()不同,它不会替换文件的内容,而是将数据添加到其中。如果找不到该文件,则它会创建该文件并将数据添加到其中。

句法:

fs.appendFile(path, data, options, callback)

参数 -

  • path – 文件的名称或路径。
  • data - 要添加到文件中的内容。
  • options - 我们一般指定编码 - ' utf-8 '
  • 回调——在我们附加文件后执行
    • 错误——如果有错误

示例 –创建一个文件app.js和一个空的output.txt文件 –

项目结构:

output.txt:最初 包含——

Learning how to write to a file. (Previous content)

应用程序.js

Javascript

const fs = require("fs");
  
const data = "\nLearning how to append to a file. (New content)";
fs.appendFile("output.txt", data, "utf-8", (error) => {
  if (error) {
    console.log(error);
  } 
  else {
    console.log("Successfully written!!");
  }
  
  fs.readFile("output.txt", "utf-8", (error, data) => {
    if (error) {
      console.log(error);
    }
    else {
      console.log(data);
    }
  });
});

使用以下命令运行app.js

node app.js

输出:我们提供的数据将附加在output.txt中,我们将得到以下输出 -

Successfully written!!
Learning how to write to a file. (Previous content)
Learning how to append to a file. (New content)

fs 模块还有许多其他方法可用于对文件执行各种类型的操作—— fs.rename() 、 fs.unlink() 、 fs.open() 、 fs.close() 等。

让我们使用文件系统模块创建一个离线判断项目:

离线法官的演示:假设您有一个 JSON 文件test-cases.json ,其中包含问题的所有输入测试用例及其输出。

项目结构——

测试用例.json

{
  "problem": 121,
  "input": [
    [5, 3, 4, 2, 1],
    [8, 100, 47, 999, 504, 771, 21, 53, 45, 660, 9],
    [0, 0, 7, 1, 4, 7, 3, 5],
    [1],
    []
  ],
  "output": [3, 673, 19, 1, 10]
}

问题陈述:找出奇数和偶数和之间的差异

Javascript

// Complete this function to find the 
// absolute difference of sum of even 
// and odd terms in arr
function diffOfOddEvenSum(arr) {
  
  // Write your code here
}

现在,要创建离线裁判,您需要创建一个app.js文件并编写代码 -

应用程序.js

const fs = require("fs");
const funct = require("./index");
function diffOfOddEvenSum(arr) {
  let odd = 0;
  let even = 0;
  
  arr.forEach((element) => {
    
    if (element % 2 == 1) {
      odd += element;
    } else even += element;
  });
  
  return odd - even;
}
  
// OFFLINE-JUDGE
// Since this is top level code we can
// use Synchronous version
// reading the data from json file
const jsonData = fs.readFileSync("test.json", "utf-8");
  
// The data we read from file is in json
// parsing the json to get the data
const testCases = JSON.parse(jsonData);
  
// Inputs is an array of input cases
const inputs = testCases.input;
  
// Exptected Output contains the correct
// output of the given problem number
const expectedOutput = testCases.output;
  
// To store the result of our input test cases
let result = "";
  
// Calling the diffOdOddEvenSum() function
// to get the output
inputs.forEach((input, index) => {
  const output = diffOfOddEvenSum(input);
  //  console.log(output)
  
  // Checking if the output is correct
  if (output == expectedOutput[index]) {
    result += `Test Case ${index + 1}- passed \n`;
  } else {
    result += `Test Case ${index + 1}- failed \n`;
  }
});
  
// We can use Synchronous version as it
// is top-level code
// writing the output to the file
fs.writeFileSync("result.txt", result, "utf-8");

使用命令运行app.js

node app.js

输出——在我们的result.txt文件中,我们有

Test Case 1- passed 
Test Case 2- passed
Test Case 3- passed 
Test Case 4- passed 
Test Case 5- failed

这样,我们就可以简单的利用文件系统核心模块创建一个离线判断工具