我正在尝试使用节点、路径和 fs 将文件写入现有目录。
它应该如何工作:
- 初始化模拟数据。
- 循环模拟数据。
- 将模拟字符串写入现有目录“输出”
- 结束程序。
工作原理:
- 初始化模拟数据。
- 循环模拟数据。
- 尝试写入现有目录。
- 产量误差:
错误:
throw new Error(`Error writing: ${err.message}`);
^
Error: Error writing: ENOENT: no such file or directory, open 'C:\Users\username\test\cheerio\output\55-207-0-228_2025-04-29_15:27:51.txt'
at C:\Users\username\test\cheerio\components\WriteFile.js:31:11
at node:fs:2385:7
at FSReqCallback.oncomplete (node:fs:188:23)
存储库
我正在使用这个存储库。处理 node:fs writefile 的函数位于/component/WriteFile.js;它在这里被调用,就在这些行中。
项目树
这是项目结构:
project-root/
├── components/
├── node_modules/
├── output/ // Target for file write.
├── .gitignore
├── index.js
├── LICENSE
├── package-lock.json
├── package.json
└── README.md
WriteFile 代码片段
为了方便起见,这里发布相关代码。WriteFile.js
const fs = require('node:fs');
const path = require('path');
const makeFile = async (fileName, { contentString, ip }) => {
const now = new Date();
const dateString =
now.getFullYear() +
'-' +
String(now.getMonth() + 1).padStart(2, '0') +
'-' +
String(now.getDate()).padStart(2, '0') +
'_' +
String(now.getHours()).padStart(2, '0') +
':' +
String(now.getMinutes()).padStart(2, '0') +
':' +
String(now.getSeconds()).padStart(2, '0');
contentString = `DATE: ${dateString}\nFor ip: ${ip}\n${contentString}`;
const filepath = path.join(
__dirname,
'..',
'output',
`${fileName}_${dateString}.txt`
);
try {
await fs.writeFile(filepath, contentString, 'utf16le', (err) => {
if (err) {
throw new Error(`Error writing: ${err.message}`);
}
});
return 'Success';
} catch (error) {
console.error('\nError:\n', error.message, '\n');
} finally {
// Code that will run regardless of try/catch result
// Remember, don't have a return in finally.
console.log('Final completed.');
}
};
module.exports = { makeFile };
调用时间:
调用地址为:
async function main() {
let start = performance.now();
let elapse;
i = 0;
for (const ip of ipList) {
i++;
if (i > 3) {
break;
}
const sleep = (ms) =>
new Promise((resolve) => {
setTimeout(resolve, ms);
});
await sleep(500);
await makeFile(ip.replaceAll('.', '-'), {
contentString: 'Mockdata',
ip: ip
});
}
elapse = performance.now() - start;
console.log('Total time elapsed: ', elapse / 1000);
}