发布于 2026-01-06 0 阅读
0

使用 JavaScript 创建后端(第 3 部分):NodeJS 文件和文件夹操作

使用 JavaScript 创建后端(第 3 部分):NodeJS 文件和文件夹操作

以下是一系列文章,旨在帮助您使用 Javascript 创建后端应用程序。

Node.js 现在已成为必备工具,因此对于开发人员来说,掌握它至关重要。

我将每两天发布一篇新文章,循序渐进地,你将学习到关于 Node.js 的所有知识。

为了不错过任何消息,请在推特上关注我:https://twitter.com/EricTheCoder_


NodeJS 中包含的模块

NodeJS 提供了多个模块及其功能,使您可以轻松执行最常见的任务。

稍后您就会发现,还可以添加社区创建的其他模块,几乎可以无限扩展应用程序的功能。

这里我只介绍几个NodeJS模块的示例。您可以查阅NodeJS官方文档了解模块的完整细节及其工作原理。https ://nodejs.org/en/docs/

路径模块

“路径”模块包含允许正确处理文件夹和文件位置的函数。

要引用模块,只需使用其名称即可。

const path = require('path')

products_path = '/data/products/products.json'
products_file = path.basename(products_path)

console.log(products_file) // products.json
Enter fullscreen mode Exit fullscreen mode

path.basename() 函数只返回文件名,在本例中为 'products.json'。

另一个方便的函数是 path.join()。此函数允许您将一个或多个文件夹和文件连接在一起。例如:

const path = require('path')

data_folder = '/data/'
products_folder  = '/products'
products_file = 'products.json'

const full_path = path.join(data_folder, products_folder, products_file)

console.log(full_path) // /data/products/products.json
Enter fullscreen mode Exit fullscreen mode

`path.join()` 使用平台特定的分隔符将所有给定的路径段连接起来,然后规范化生成的路径。

最后,有时您可能需要在服务器上使用绝对路径。

const path = require('path')

data_folder = '/data/'
products_folder  = '/products'
products_file = 'products.json'

const full_path = path.join(data_folder, products_folder, products_file)

const abs_path = path.resolve(__dirname, 'data', 'products', 'products.json')

console.log(abs_path)
// /Users/username/Documents/dev/learn_node/data/products/products.json
Enter fullscreen mode Exit fullscreen mode

path.resolve() 从右到左处理路径序列,将每个后续路径添加到前面,直到构造出一个绝对路径。

文件系统模块

毫无疑问,该模块是最常用的模块之一,它允许您处理服务器上的文件和文件夹。

FS模块允许以两种不同的方式操作文件和文件夹。您可以采用同步模式或异步模式进行操作。

同步函数

这意味着该函数是阻塞式的,NodeJS 将等待函数返回值后再恢复应用程序的执行。

异步函数

这意味着 NodeJS 不会等待函数返回值,而是会继续执行应用程序,并在函数完成后处理结果。

应该采用哪种方法?

这取决于您要开发的应用程序类型。例如,如果您正在开发一个 Web 服务器,那么使用异步函数是最佳选择,甚至可以说是必不可少。同步函数不仅会阻塞当前用户的服务器运行,还会阻塞所有用户的服务器运行。

另一方面,在某些非常特殊的情况下,使用同步函数是合理的。例如,在启动 Web 服务器之前,如果需要读取配置文件,那么同步函数可以确保在服务器启动之前读取该文件。

简而言之,通常情况下,总是使用异步函数,只有在必要时才使用同步函数。

让我们来看一个使用“fs”模块处理两种类型函数的例子:

同步函数

// app.js

const fs = require('fs')

const data = fs.readFileSync('info.txt', 'utf-8')
console.log(data) // file content
console.log('The file has been read')
Enter fullscreen mode Exit fullscreen mode

结果很容易预测,代码将逐行执行。

异步函数

const fs = require('fs')

const info = fs.readFile('info.txt', 'utf-8', (err, data) => {
    console.log(data)
})
console.log('The file has been read')
Enter fullscreen mode Exit fullscreen mode

在这里,NodeJS 不会等待函数返回结果就继续执行。

这将导致首先显示“文件已读取”,当 readFile() 完成读取后,NodeJS 将执行回调函数 console.log(data)。

读取和创建文件

请注意,在本教程的其余部分,我们将只使用异步函数。

首先,我们将创建一个文本文件。为此,我们将使用 writeFile 函数。

const fs = require('fs')

const data = 'This is my Hello World file'

fs.writeFile('info.txt', data, 'utf-8', (err) => {
    console.log('File created')
})
Enter fullscreen mode Exit fullscreen mode

writeFile() 函数的功能非常直观。您必须指定文件名、数据内容和编码选项(文本格式使用 utf-8)。

运行此代码后,将在当前文件夹中创建 info.txt 文件。

这样就可以使用 readFile 函数读取该文件了。

const fs = require('fs')

const info = fs.readFile('info.txt', 'utf-8', (err, data) => {
    console.log(data)
})
Enter fullscreen mode Exit fullscreen mode

如果文件不存在,您可以返回错误。

const info = fs.readFile('info.txt', 'utf-8', (err, data) => {
    if (err) 
        console.log(err)
    else
        console.log(data)
})
Enter fullscreen mode Exit fullscreen mode

也可以使用 readFile 函数,但通过 Promise 来读取文件。

const fs = require('fs').promises

const start = async () => {
    const data = await fs.readFile('info.txt', 'utf8')
    console.log(data)
}

start()
Enter fullscreen mode Exit fullscreen mode

导入方式不同,语法也不同,但结果相同。

复制文件

要复制文件,我们使用 copyFile 函数。

fs.copyFile('info.txt', 'info2.txt', (err) => {
      if (err) return console.error(err)
        console.log('File copied')
})
Enter fullscreen mode Exit fullscreen mode

创建一个文件夹

我们使用 mkdir 函数来创建文件夹。

fs.mkdir('data', (err) => {
    console.log('Data folder created')
})
Enter fullscreen mode Exit fullscreen mode

文件夹创建在当前文件夹内

列出文件夹中的文件

可以获取文件夹中的文件列表

fs.readdir('.', (err, files) => {
    console.log(files)
})
Enter fullscreen mode Exit fullscreen mode

'.' 表示当前文件
,files 是一个包含所有文件夹文件名的数组。

重命名文件

要重命名文件,我们使用 rename() 函数。

fs.rename('info.txt', 'data.txt', (err) => {
    if (err) return console.log(err)
    console.log('File renamed')
})
Enter fullscreen mode Exit fullscreen mode

可能性几乎是无穷无尽的!

现在您已经掌握了 'fs' 模块。如果您想了解所有可用的 'fs' 函数,请访问 NodeJS 网站查看详细信息:
https://nodejs.org/api/fs.html

结论

今天就到这里,请在推特上关注我:https://twitter.com/EricTheCoder_,以便在下一篇文章发布时收到通知(两天内)。

文章来源:https://dev.to/ericchapman/create-a-backend-in-javascript-nodejs-files-and-folders-manipulation-3782