Skip to content
Bite-Sized Musings

TIL: Writing Utility Scripts in Node.js

javascript, es6, chunk, process, nodejs, code snippet, today-i-learned1 min read

Context:

(Copypasta from the other shell script post!) Was writing a script to pull metadata from an NFT collection.

I had to write a loop that queried the API for the asset ID, which then generated JSON files in batches of 10, now prepopulated with asset IDs. These weren't in proper JSON format yet, so I had to add the array brackets at the start and end of the file. Also had to account for customization (in case we want to try querying for another NFT project).

It was one of those rare times I get to write a utility script with no RESTful API involved, a.k.a., not work.

Use command-line arguments when running node script

SO Answer

My implementation:

1// ENV VAR
2const args = process.argv.slice(2);
3
4const policyId = args[0];

When running it on Terminal:

1node 02_generate_batch_queries.js <POLICY_ID>

Then some quick and simple code for chunking, ref: SO Answer:

1// generate query strings that will output to specific batch files
2const result = fullArray.reduce((resultArray, item, index) => {
3 const chunkIndex = Math.floor(index / CHUNK_SIZE);
4 if (!resultArray[chunkIndex]) {
5 resultArray[chunkIndex] = []; // start a new chunk
6 }
7
8 const textQuery = `${queryString}${item.asset} >> ${METADATA_FILE_PREFIX}${chunkIndex}.json`;
9
10 resultArray[chunkIndex].push(textQuery);
11 return resultArray;
12}, []);

Read more:

© 2022 by Bite-Sized Musings. All rights reserved.
Theme by LekoArts