Node.js 如何访问文件系统

Node.js 如何访问文件系统

在本文中,我们将介绍如何在NodeJS中访问文件系统以及如何执行一些有用的文件操作。

先决条件:

  • 基本了解ES6
  • 基本了解NodeJS

NodeJS是运行在JavaScript V8引擎上的最受欢迎的服务器端编程框架之一,它使用单线程的非阻塞I/O模型。我们可以使用一些内置模块在NodeJS中访问文件系统。

文件系统: 一个文件是存储在辅助存储器中的相关信息的集合,或者是一组与文件一起工作并对其进行管理的类似类型的实体的集合,也被称为文件系统。

如果您想更多地了解文件系统,请参考此文章。

文件系统模块(fs模块): 用于在NodeJS中处理文件系统的内置模块之一是文件系统模块,简称为“fs”模块。fs模块非常强大,可以在NodeJS中执行与文件系统相关的任何任务。

在Node JS中访问文件系统意味着对文件执行一些基本操作,也称为CRUD操作。

CRUD操作:

  • C => 创建文件
  • R => 读取文件
  • U => 更新文件
  • D => 删除文件

使用“fs”模块对文件进行基本操作:

步骤1: 创建一个扩展名为“.js”的文件。

Node.js 如何访问文件系统

步骤2: 将“fs”模块添加到代码库中。

语法:

const fs = require('fs');

在引入fs模块后,您可以对文件执行以下操作:

步骤1: 创建文件

语法:

const fs = require('fs');
fs.writeFileSync('./{file_name}', 'Content_For_Writing');

fs.writeFileSync方法用于将内容写入文件,但是如果文件不存在,它会创建新文件并写入内容。

Node.js 如何访问文件系统

步骤2: 读取文件

语法:

const fs = require('fs');
const file_content = fs.readFileSync('./{file_name}', 
    '{content_formate}').toString();

// For show the data on console
console.log(file_content);

fs.readFileSync方法用于从文件中读取数据,readFileSync的第一个参数是文件路径,第二个参数采用 {format, flag, etc} 选项,并返回流的缓冲区对象。因此我们可以使用toString()方法将缓冲区字符串赋给一个名为file_content的变量,然后使用console.log()方法将数据显示在控制台上。

Node.js 如何访问文件系统

步骤3: 更新文件

语法:

const fs = require('fs');
fs.appendFileSync('./{file_name}', " {Updated_Data}");

const file_content = fs.readFileSync(
    './{file_name}', '{file_formate}').toString();

console.log(file_content);

fs.appendFileSync方法用于更新文件的数据。

Node.js 如何访问文件系统

步骤4: 删除一个文件

const fs = require('fs');
fs.unlinkSync('./{file_name}');

使用fs.unlinkSync()方法通过传递文件名来删除文件。

Node.js 如何访问文件系统

下面是上述操作的代码实现:

示例:

文件名是index.js

const fs = require('fs');
 
/* The fs.writeFileSync method is used 
to write something to the file, but if
the file does not exist, it creates new 
files along with writing the contents */
fs.writeFileSync('./testfile', 'This is a file');
var file_content = fs.readFileSync(
        './testfile', 'utf8').toString();
 
console.log(file_content);
 
/* The fs.appendFileSync method is used 
for updating the data of a file */
fs.appendFileSync('./testfile', " Updated Data");
file_content = fs.readFileSync(
    './testfile', 'utf8').toString();
console.log(file_content);
 
/* The fs.unlinkSync method are used to delete 
the file. With passing the file name */
fs.unlinkSync('./testfile');

使用以下命令尝试并通过node.js运行该代码:

node index.js

最后,我们看到了如何访问文件系统,并尝试了许多操作。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程