为 Node.js 中数组的每个元素写一个文件

Write a file for each element of an array in Node.js

我对 Node.js 完全陌生。这可能真的很容易,但我无法让它发挥作用。我想为数组中的每个元素创建一个名为“employee.txt”的空文件。我正在使用 writeFileSync 和 forEach 循环,但它只创建了 1 个文件,其中包含最后一个元素。

下面是我的代码。非常感谢!

const fs = require ('fs')
let employees = ['Daniel', 'Sarah', 'Julia', 'Rob', 'Alex']

employees.forEach (employee => {
  fs.writeFileSync('employee.txt',employee+"\r\n")
}) 

尝试将文件重命名为不同的名称,例如

const fs = require ('fs');
let employees = ['Daniel', 'Sarah', 'Julia', 'Rob', 'Alex'];

employees.forEach (employee => {
  fs.writeFileSync(`${employee}.txt`, employee+"\r\n")
});

这样每个文件都将以员工姓名命名。如果您要有多个同名员工,也可以使用索引

employees.forEach ((employee, index) => {
  fs.writeFileSync(`${employee} ${index}.txt`, employee+"\r\n")
});