gpt4 book ai didi

javascript - 尝试从文件读取数据时,readFileSync 返回未定义

转载 作者:行者123 更新时间:2023-12-01 00:13:37 26 4
gpt4 key购买 nike

我在名为 data 的目录下创建了多个函数并用名为 generatedRandomData 的函数返回的一些随机数据填充它们。为了创建多个文件,我编写了这些函数:

const createFile = (fileName, data) => {
if (fs.existsSync(fileName)) throw new Error('Filename already exists');
fs.writeFile(fileName, data, {
encoding: 'utf8',
flag: 'w',
}, (error) => {
if (error) return error;
console.log('File created successfully');
return null;
});
};

const createFiles = (dirPath, sizeList) => {
if (sizeList && !sizeList.length) throw new Error('The list of size should not be empty');

const fileCreationPromises = sizeList.map(async (size) => {
const data = generateRandomData(size);
const fileName = resolve(dirPath, `./data_${size}.txt`);
await createFile(fileName, data);
});
return Promise.all(fileCreationPromises);
};

然后我调用函数 generateData为了生成随机数据并调用上述函数,然后创建文件:

const generateData = async (dirPath, sizeList) => {
if (!dirPath) throw new Error('No directory path was provied');
if (!sizeList || (sizeList && !sizeList.length)) throw new Error('Size list should not be empty');
await createFiles(dirPath, sizeList);
};

我调用另一个名为 execute 的函数它从这些文件中读取数据以继续处理:

const execute = async (func, dirPath, label) => {
const files = fs.readdirSync(dirPath);
const result = [];
if (files && files.length) {
for (const file of files) {
const filename = resolve(dirPath, `./${file}`);
const parsedData = readDataFromFile(filename);
const data = parsedData.split(',').map((d) => Number(d));
const { length } = data;

result.push({
label: length,
value: getExecutionTime(func, data),
});
}
}
await createFile(resolve(dirPath, `./${label}`), result);
};

最后,我调用函数 initialize :

const { resolve } = require('path');
const fs = require('fs');
const { generateData, sizeList, execute } = require('../utils/helpers');
const { underscorePartial } = require('../main/partial');

const dirPath = resolve(__dirname, '../data');

const initialize = () => {
if (!fs.existsSync(dirPath)) {
fs.mkdir(dirPath, async (error) => {
if (error) throw error;
await generateData(dirPath, sizeList);
await execute(underscorePartial, dirPath, 'uExecutionTime.txt');
});
}
};

try {
initialize();
} catch (error) {
console.log(error);
}

但是我意识到uExecutionTime.txt在最后一步中创建的内容包含 undefined由于功能 readDataFromFile返回 undefined 。我猜是readDataFromFile在数据创建完成之前开始从文件中读取。有任何修复我的代码的建议或者代码中是否有任何遗漏或错误的内容?

最佳答案

问题出在你的createFile函数上。当它没有返回 promise 时,你关心等待它。这是一种回调风格。它应该被包裹在 promise 中。

const createFile = (fileName, data) => {
if (fs.existsSync(fileName)) throw new Error('Filename already exists');
return new Promise((resolve, reject) => {
fs.writeFile(fileName, data, {
encoding: 'utf8',
flag: 'w',
}, (error) => {
if (error) reject(error);
console.log('File created successfully');
resolve(null);
});
});
};

希望这能解决问题。

关于javascript - 尝试从文件读取数据时,readFileSync 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59918700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com