我正在构建一个React / Redux应用程序,除其他外,该应用程序在单击按钮时会发出声音。我正在尝试使用nodejs fs.readdirSync模块来制作包含文件路径和title属性的对象数组。当我使用node运行以下代码时,它本身运行良好:
const path = require('path');
const fs = require('fs');
const directoryPath = path.join(__dirname, '/electro');
const files = fs.readdirSync(directoryPath);
const re = /(?<=-\d\d-)(.*)(?=.wav)/g;
const drumObjects = [];
files.forEach((file) =>{
drumObjects.push({
name:file.match(re)[0],
path: `${ process.cwd()}/${directoryPath}/${file}`
})
});
console.log(drumObjects);
exports.drumObjects = drumObjects;
接下来,我尝试将drumObjects
数组导入我的化简器并将其设置为itialstate,但是当我这样做时,我在浏览器控制台中收到以下错误:
ElectroKit.js:7 Uncaught TypeError: fs.readdirSync is not a function
at Object.eval (ElectroKit.js:7)
at eval (ElectroKit.js:20)
at Object../src/drum_audio/ElectroKit.js (transformed.js:1937)
at __webpack_require__ (transformed.js:725)
at fn (transformed.js:102)
at eval (root_reducer.js:13)
at Object../src/reducers/root_reducer.js (transformed.js:1961)
at __webpack_require__ (transformed.js:725)
at fn (transformed.js:102)
at eval (store.js:9)
我已经进行了大量的Google搜索,并观看了一些有关Node.js工作原理的视频,但目前看来,这是我学习的一个非常重要的主题。谁能告诉我最好的方法:遍历文件夹中的文件,基于这些文件创建对象数组,然后将其加载到redux reducer初始状态?
非常感谢SO专家, 乔尔