文件命名为node.js
In this blog post I’m going to explain how to rename a set of files.
在这篇博客中,我将解释如何重命名一组文件。
The same process works to move files to another folder, because when you rename you rename the path of the file.
相同的过程可以将文件移动到另一个文件夹,因为重命名时会重命名文件的路径。
The motivation for this task was this: in Hugo we can write blog posts as files, like this:
这项任务的动机是这样的:在Hugo中,我们可以将博客文章作为文件编写,如下所示:
first-post.md
second-post.md
third-post.md
We can also add them to a folder that contains an index.md
file:
我们还可以将它们添加到包含index.md
文件的文件夹中:
first-post/
> index.md
second-post/
> index.md
third-post/
> index.md
The difference is that with folder we can add images and associate them more easily to a blog post.
区别在于,通过文件夹,我们可以添加图像并将其更轻松地关联到博客文章。
I could have done the change manually, but I had about 50 files in the folder and I didn’t really want to do that job.
我本可以手动进行更改,但是该文件夹中大约有50个文件,我真的不想做这项工作。
I wanted it to happen automatically.
我希望它能够自动发生。
Let’s start by requiring one core module we’re going to use: fs
. As it is a core module, there’s no need to npm install
it.
首先,我们需要一个将要使用的核心模块: fs
。 由于它是核心模块,因此不需要npm install
它。
const fs = require('fs')
Then, get a reference to the current folder. I suppose we’re going to run the script in the same folder where we want to perform this change.
然后,获取对当前文件夹的引用。 我想我们将在要执行此更改的文件夹中运行脚本。
__dirname
is the variable that always points to the current working folder.
__dirname
是始终指向当前工作文件夹的变量。
I get a list of all the files and folders:
我得到所有文件和文件夹的列表:
const files = fs.readdirSync(__dirname)
Then I filter out only the items that end with .md
:
然后,我仅过滤出以.md
结尾的项目:
for (const file of files) {
if (file.endsWith('.md')) {
console.log(file)
}
}
Once we have the file
reference, which represents the filename, we can call fs.rename()
.
一旦有了代表文件名的file
引用,就可以调用fs.rename()
。
This function accepts 3 parameters:
此函数接受3个参数:
- the current path 当前路径
- the path we want to move to 我们要移动的路径
- an callback fired if there’s an error 发生错误时触发的回调
The current path is:
当前路径是:
__dirname + '/' + item
The path we want to move to is:
我们要移动的路径是:
__dirname + '/' + item.replace('.md', '') + '/index.md'
See? We create a new folder from the file name, then we append index.md
:
看到? 我们从文件名创建一个新文件夹,然后添加index.md
:
fs.rename(
__dirname + '/' + item,
__dirname + '/' + item.replace('.md', '') + '/index.md',
err => {
console.log(err)
}
)
Here’s the full code:
这是完整的代码:
const fs = require('fs')
const files = fs.readdirSync(__dirname)
for (const file of files) {
if (file.endsWith('.md')) {
fs.rename(
__dirname + '/' + item,
__dirname + '/' + item.replace('.md', '') + '/index.md',
err => {
console.log(err)
}
)
}
}
文件命名为node.js