首页 > 解决方案 > Generating a json for a icon cheatsheet

问题描述

I'm trying to generate a json file containing the filenames of all the files in a certain directory. I need this to create a cheatsheet for icons.

Currently I'm trying to run a script locally via terminal, to generate the json. That json will be the input for a react component that will display icons. That component works, the create json script doesn't.

Code for generating the json

const fs = require('fs');
const path = require('path');

/**
 * Create JSON file
 */
const CreateJson = () => {
  const files = [];
  const dir = '../icons';

  fs.readdirSync(dir).forEach(filename => {
    const name = path.parse(filename);
    const filepath = path.resolve(dir, filename);
    const stat = fs.statSync(filepath);
    const isFile = stat.isFile();

    if (isFile) files.push({ name });
  });

  const data = JSON.stringify(files, null, 2);
  fs.writeFileSync('../Icons.json', data);
};

module.exports = CreateJson;

I run it in terminal using "create:json": "NODE_ENV=build node ./scripts/CreateJson.js"

I expect a json file to be created/overridden. But terminal returns:

$ NODE_ENV=build node ./scripts/CreateJson.js ✨ Done in 0.16s.

Any pointers?

标签: node.jsjsonreactjs

解决方案


You are creating a function CreateJson and exporting it, but you are actually never calling it.

You can get rid of the module.exports and replace it with CreateJson().

When you'll execute the file with node, it will see the function declaration, and a call to it, whereas with your current code there is no call.


推荐阅读