Hello everyone, I am the front-end Xigua brother. Recently I have a personal need to write a small script.
I have a personal static blog website generated based on hexo. I want to add a piece of advertising copy to the end of all articles in the blog. I don’t want to write such a meaningless script, so I asked ChatGPT to help me. Write a short script.
Because I am a front-end developer, I chose to let ChatGPT generate the nodejs script for me. Other sh and python are also available, but I’m not familiar with them, so I can’t confirm whether the code meets the requirements.
The description is very concise, and the results given by ChatGPT look good.
But then I found that I had not provided a detail, that is, the file path needs to be provided in the file. I'm looking forward to passing in the path via command line parameters, because in the bash environment, the path can be completed via the tab key, which is convenient and less error-prone.
Thanks to ChatGPT’s contextual association capabilities, we can add new requirements based on the above questions.
Use cases are also provided:
<code>const fs = require('fs');const path = require('path');// 从命令行参数中获取文件夹路径const directoryPath = process.argv[2];if (!directoryPath) {console.error('请提供要处理的文件夹路径');process.exit(1);}const suffix = '\n\n这是添加的字符串。'; // 将要添加的字符串放在这里fs.readdir(directoryPath, (err, files) => {if (err) {console.error(`无法读取目录:${directoryPath}`, err);return;}// 仅处理 Markdown 文件const markdownFiles = files.filter(file => path.extname(file).toLowerCase() === '.md');markdownFiles.forEach(file => {const filePath = path.join(directoryPath, file);// 读取文件内容fs.readFile(filePath, 'utf8', (err, data) => {if (err) {console.error(`无法读取文件:${filePath}`, err);return;}// 将字符串添加到文件末尾const content = `${data.trim()}${suffix}`;// 将更改保存回原始文件fs.writeFile(filePath, content, 'utf8', err => {if (err) {console.error(`无法写入文件:${filePath}`, err);return;}console.log(`已更新文件:${filePath}`);});});});});</code>
Copy the code to the js file I created, and replace the suffix inside with the content you need to fill.
Then execute:
<code>node scripts/add-footer-qrcode.js source/_posts</code>
You can see that this text is added to the end of more than 100 md files in the folder.
I am the front-end Xigua brother. Welcome to follow me and experience the rapid changes of AI.
ChatGPT is used to write simple scripts or algorithms, which is awesome.
If you ask me to write it, it will still take a lot of time. There are many small details in it. If you write it quickly and test it, it will take half an hour. But ChatGPT is here and it will be written for you in 10 seconds. Let’s copy it and it will work if we modify it, or even without modification!
The above is the detailed content of Use ChatGPT to generate a small script, copy it directly and use it. For more information, please follow other related articles on the PHP Chinese website!