node.js fs模块_Node.js中的fs模块简介

node.js fs模块

fs, short for File System, is one of the most basic and useful modules in Node. In this article, we’ll go over some of the most important and useful methods for manipulating the file system.

fs是File System的缩写,是Node中最基本,最有用的模块之一。 在本文中,我们将介绍一些用于操纵文件系统的最重要和最有用的方法。

入门 (Getting Started)

You’ll need to have Node.js installed first, of course. You can do that here. Luckily for us, fs is one of the ‘out-of-the-box’ modules that come with Node so it is already available to you.

当然,您需要首先安装Node.js。 你可以在这里做。 对我们来说幸运的是,fs是Node随附的“即用型”模块之一,因此您已经可以使用它。

const fs = require('fs');

同步与异步 (Synchronous vs Asynchronous)

Every fs method has both a synchronous and an asynchronous version with the name for the synchronous form just ending with Sync. So an asynchronous fs.writeFile() becomes fs.writeFileSync(). Of course, Synchronous code will stop later code from running when there is an error, but they’re simpler to get the hang of so for all of the examples in this article we’ll be using their synchronous forms.

每个fs方法都具有同步版本和异步版本,其同步形式的名称仅以Sync结尾。 因此,异步fs.writeFile()变为fs.writeFileSync() 。 当然,当出现错误时,同步代码将阻止以后的代码运行,但是它们更易于掌握,因此对于本文中的所有示例,我们将使用其同步形式。

基本操作 (Basic Operations)

The basic CRUD operations (create, read, update, and delete) are very simple to do with only 3 main functions.

基本的CRUD操作(创建,读取,更新和删除)非常简单,只需3个主要功能即可完成。

  • fs.writeFileSync()

    fs.writeFileSync()

  • fs.readFileSync()

    fs.readFileSync()

  • fs.unlinkSync()

    fs.unlinkSync()

fs.writeFileSync() (fs.writeFileSync())

fs.writeFileSync() only takes two arguments; the path to the new file’s location, which must end with the name of the new file and the data you want stored.

fs.writeFileSync()仅接受两个参数; 新文件位置的路径,必须以新文件名和要存储的数据结尾。

gator.js
gator.js
const gators = [{
  type: 'cayman'
}];

fs.writeFileSync('./swamp/cayman.json', JSON.stringify(gators));

Result:

结果:

swamp/cayman.json
沼泽/cayman.json
[{"type":"cayman"}]

Keep in mind that fs.writeFileSync() is completely rewriting the content in cayman.json so if you change type: 'cayman' to type: 'croc' and re-run the file, cayman will be replaced. This can have significant performance drawbacks when modifying large files.

请记住, fs.writeFileSync()完全重写了cayman.json中的内容,因此,如果将type: 'cayman'更改为type: 'croc'并重新运行文件,cayman将被替换。 修改大文件时,这可能会带来明显的性能缺陷。

fs.readFileSync() (fs.readFileSync())

By default all data is returned as a 'buffer’, a special encoded string of numbers, to fix this just pass 'utf8’ as the second argument.

默认情况下,所有数据都以“缓冲区”(特殊编码的数字字符串)形式返回,以解决此问题,只需将“ utf8”作为第二个参数即可。

Here we’re going to return a empty array if cayman.json is empty and return the data if it exists.

在这里,如果cayman.json为空,我们将返回一个空数组,如果cayman.json则返回数据。

gator.js
gator.js
const gators = [{
    type: 'cayman'
}];


const getData = () => {
  let data = fs.readFileSync('./swamp/cayman.json', 'utf8');

  if (!data) return [];
  else {
    const file = JSON.parse(data);
    return file;
  }
}

const data = getData();

unlinkSync() (unlinkSync())

Unlink is the simplest of the three, only requiring the path to the file or symbolic link you wish to remove.

取消链接是这三个中最简单的,只需要您要删除的文件或符号链接的路径即可。

fs.unlinkSync('./swamp/cayman.json');

文件夹上的CRUD操作 (CRUD Operations On Folders)

The above three methods have their own useful counterparts for manipulating directories themselves.

上面三种方法都有自己的有用的对应物,它们可以自己操纵目录。

  • fs.mkdirSync()

    fs.mkdirSync()

  • fs.rmdirSync()

    fs.rmdirSync()

  • fs.readdirSync()

    fs.readdirSync()

Since the usage of fs.mkdirSync() and fs.readdirSync() are the same as their file counterparts we’ll finish up with working out the gotchas that come with fs.rmdirSync() instead.

由于fs.mkdirSync()fs.readdirSync()的用法与文件对应的用法相同,因此我们将最终解决fs.rmdirSync()附带的陷阱。

rimraf vs fs.rmdirSync() (rimraf vs fs.rmdirSync())

The main problem with using fs.rmdirSync() to delete folders is the fact that it will only work on empty directories. If you were to try using it to remove ./swamp it will return:

使用fs.rmdirSync()删除文件夹的主要问题是它仅适用于空目录。 如果您尝试使用它删除./swamp ,它将返回:

Error: ENOTEMPTY: directory not empty, rmdir './swamp'

which obviously isn’t what we want. Sadly, Node does not have a native solution for this, for some reason, so we’ll have to look elsewhere.

这显然不是我们想要的。 可悲的是,由于某种原因,Node对此没有本机解决方案,因此我们将不得不寻找其他地方。

The simplest solution I’ve found has been an npm package called rimraf, so let’s install that quickly.

我找到的最简单的解决方案是一个名为rimraf的npm软件包,因此让我们快速安装它。

$ npm i rimraf

The syntax is very similar, except instead of fs you call rimraf.sync() ( or plain rimraf() for the asynchronous version) and pass in your path as you would expect.

语法非常相似,除了调用fs而不是fs之外,您可以调用rimraf.sync() (对于异步版本,则调用普通的rimraf() ),然后按预期方式传递路径。

const rimraf = require('rimraf');

rimraf.sync('./swamp');

结论 (Conclusion)

With just these few functions you’ll be able to handle many of the common use cases with manipulating files and their data.

仅需这几个功能,您就可以通过处理文件及其数据来处理许多常见的用例。

Any introduction to a new technology will come with obligatory referral to the documentation (it really is one of the best ways to explore something).

对新技术的任何介绍都必须附带文档 (它确实是探索某些事物的最佳方法之一)。

翻译自: https://www.digitalocean.com/community/tutorials/nodejs-intro-to-fs-module

node.js fs模块

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值