使用require动态拼接地址引入JSON文件 - Node.js教程
你可以使用require函数来引入JSON文件,并使用动态拼接的方式来构建文件路径。下面是一个示例代码:
const fs = require('fs');
function loadJsonFile(fileName) {
const filePath = 'path/to/files/' + fileName + '.json';
const jsonContent = fs.readFileSync(filePath, 'utf-8');
return JSON.parse(jsonContent);
}
const fileName = 'data';
const json = loadJsonFile(fileName);
console.log(json);
在上面的示例中,我们定义了一个loadJsonFile函数,它接受一个文件名作为参数。函数内部使用动态拼接的方式构建文件路径,并使用fs.readFileSync函数读取文件内容。然后,我们使用JSON.parse将文件内容解析为JSON对象,并将其返回。
你可以根据需要修改filePath的拼接逻辑,以适应你的文件路径结构。
原文地址: https://www.cveoy.top/t/topic/pIzC 著作权归作者所有。请勿转载和采集!