Is there a way to access and read all JSON files within a directory in a Meteor application?

Is there a way to read all JSON files within a folder in my Meteor application?

This is the structure I currently have:

/server  
-- /methods  
-- -- file1.json  
-- -- file2.json  

I've attempted to read all JSON files using this code snippet:

var fs = Npm.require('fs');
var path = Npm.require('path');
var base = path.resolve('.');

try {
    var files = fs.readdirSync(base + '/methods/*.json');
    console.log(files);
} catch (e) {
    console.dir(e)
}

However, I am encountering an error stating that the directory or file does not exist.

Am I missing something here? Or perhaps there is an alternative method to achieve this task? Any guidance would be appreciated.

Answer №1

Before proceeding, it's important to exercise caution when determining the root of Meteor's project, as the results yielded by path.resolve('.') or process.env.PWD can vary across different deployment configurations.

Additionally, when using the path argument in fs.readdirSync(path), it must specify a directory. Therefore, a correct invocation would be

var files = fs.readdirSync(base + '/server/methods/');
.

Nevertheless, I suggest utilizing Assets. Simply relocate your JSON files to the private directory and access them on the server through

Assets.getText(assetPath, [asyncCallback])
or
Assets.getBinary(assetPath, [asyncCallback])
.

For instance:

if (Meteor.isServer) {
    Meteor.startup(function() {
        var example1 = JSON.parse(Assets.getText('methods/example1.json'));
        var example2 = JSON.parse(Assets.getText('methods/example2.json'));
        console.log(example1);
        console.log(example2);
    });
}
...and so forth... Assuming that your project structure resembles:
project-root
├── .meteor
├── server
├── private
│   └── methods
│       └── example1.json
│       └── example2.json
└── …

Answer №2

After referring to Matthias Eckhart's answer, I created a method that reads and converts all csv files within a specified folder into JSON format. This method then returns the data as an object with a child object representing each csv file. Sharing it here in case it proves helpful to others: encountering some challenges while handling Assets and methods, especially during csv to JSON conversion.

import CSVToJSON from 'csvtojson';

if (Meteor.isServer) {
    const retrieveFilenames = (options, callback) => {
        // accessing contents of the 'private/parameters' directory
        const { exec } = Npm.require('child_process');

        // filtering out directories from the results of "ls -m" command before loading files
        exec('ls -m assets/app/parameters | tr -d \' \n\' ', Meteor.bindEnvironment((error, stdout, stderr) => {
            if (error !== null) {
                console.log(`Error in retrieveFilenames: ${error}`);
            }
            const filenames = stdout.split(',');
            callback(null, filenames);
        }));
    };

    Meteor.methods({
        'loadParameters'() {
            const syncFunc = Meteor.wrapAsync(retrieveFilenames);
            const filenames = syncFunc({});

            const promises = [];
            const filesData = [];

            filenames.forEach((filename) => {
                if (filename.split('.').pop() === 'csv') {
                    filesData.push(Assets.getText(`parameters/${filename}`));
                }
            });

            filesData.forEach((data) => {
                promises.push(CSVToJSON().fromString(data));
            });

            return Promise.all(promises)
                .then((results) => {
                    const parameters = {};

                    results.forEach((result) => {
                        const data = result[0];
                        const parameter = { ...data };
                        delete parameter.propertyName;
                        parameters[data.propertyName] = parameter;
                    });

                    return parameters;
                });
        },
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The process of querying two MySQL tables simultaneously in a Node.js environment using Express

My goal is to display both the article and comments when a user clicks on a post. However, I've encountered an issue where only the post loads without the accompanying comments. Here is the code snippet that I've been working with: router.get(&a ...

Troubleshooting Problems with Google Maps and Javascript/JSON in Internet Explorer

Currently, I am utilizing the Google Maps API to construct a map that displays store locations in close proximity to a user-specified location. Everything is functioning properly, however, I am encountering an error in Internet Explorer that I would like t ...

Generate a random 8-digit number with a specific range in JavaScript

I want to generate a random 8-digit number ranging from 0 to 7, excluding the numbers 8 and 9. Here is what I have tried so far, but I'm unable to exclude the numbers 8 and 9: var b = Math.floor(Math.random()*90000000) + 10000000; console.log(b) Is ...

What is the process for locating the src value of an image that has been uploaded utilizing fileReader?

I am currently working on a program that empowers the user to select an image for uploading. Once the user chooses an image, it activates the previewFile() function, which makes use of FileReader to display the selected image. Now, I'm in the process ...

A recursive approach for constructing a tree structure in Angular

Currently, I am working on a project involving the implementation of crud functions. To display the data in a tree-like structure, I am utilizing the org chart component from the PrimeNg library. The data obtained from the backend is in the form of an arra ...

Troubleshooting issue with C# Ajax success response not triggering alert

I am facing an issue where the alert box for success does not show even though the code successfully inserts contact details using ajax and C#. Strangely, when I debug through the JavaScript debugger in Chrome, the alert pops up as expected. Here is the co ...

What is the best way to pass a bind value in an Angular function controller?

I am new to working with AngularJS and I'm trying to pass a model bind value into a function declared in the controller. However, when I try to access that value from the controller, it returns undefined. Here is the code snippet: HTML: <div> ...

Exploring Angular controllers, promises, and testing

Currently, I am in the process of writing some unit tests for my controller that utilizes promises. The code snippet in question is as follows: UserService.getUser($routeParams.contactId).then(function (data) { $scope.$apply(function () { $sco ...

exchange the class using only JavaScript

I need help with a code snippet that allows for swapping classes using a loop. The objective is to click on the brown square causing it to move to the position of the blue square, while the blue square moves to the previous position of the brown square. T ...

Encountering issues while creating a basic digital clock webpage using React

I am trying to create a simple clock in React, but I want all the time data to be stored in a single object instead of separate states for hours, minutes, and seconds. However, I keep running into an error. Can someone please assist me? import React from & ...

Is a 'Virtual DOM' included in React Native's architecture?

According to the ReactJS wiki page on Virtual DOM: React uses an in-memory cache of data structures to efficiently compute differences and update the displayed DOM in the browser. This allows developers to write code as if the entire page is re-rendered ...

Constructing a basic electrical circuit with the help of Three.JS

As someone who is new to the Three.js library, I am looking to create a circuit using batteries, bulbs, ammeter, and switches with some basic features like glowing bulbs when the circuit is closed and toggling button states when clicked. I have searched ...

What are some tactics for avoiding movement in the presence of a border setting?

I created a webpage that has the following structure: .topbar-container { width: 100%; position: fixed; top: 0; background-color: #2d3e50; z-index: 999; display: flex; transition: height 500ms; } @media (min-width: 992px) { .topbar-cont ...

Angular renders HTML elements

Greetings! I am currently experimenting with using AngularJS for the frontend and Wordpress as the backend of my project. To load content from Wordpress into Angular, I am utilizing a JSON wordpress plugin along with making $http requests. The content th ...

Angular 12: Running ng test shows code coverage error - TypeError: Unable to access 'initialize' property as undefined

I encountered an error in the code coverage console: TypeError: Cannot read properties of undefined (reading 'initialize') I am trying to call a service method from the component.ts file The code in the component.ts file looks like: this.myAuth ...

Create a CSS menu that centers the links

Here is the CSS code I am using for my horizontal menu: nav { height: 40px; width: 100%; background: #F00; font-size: 11pt; font-family: Arial; font-weight: bold; position: relative; border-bottom: 2px solid # ...

Utilize Python to search and substitute text in numerous CSV files

I have approximately 40 CSV files along with a separate file containing 'find' and 'replace' data. The find column holds the values that need to be located, while the replace column stores the text for replacement. Is there a method to ...

How to Convert Blob/Varbinary to an Image on Android devices

I am working on displaying an image sent to me via a web service in JSON format. The snippet of the image data looks like this: {"notif_detailsResult":[{"image":[255,216,255,224,0,16,74,.... I need to show this image on an ImageView in my Android app ...

Responsive menu not collapsing properly and appearing funky in Drupal

I've managed to create a responsive navigation bar, but I'm encountering two issues. Firstly, when I resize the screen on my test pages, not all of the links hide as expected. Secondly, after inserting the code into Drupal, the nested links appea ...

Run Javascript code if a specific CSS class is present on an element

Whenever a user enters an incorrect value into a textbox on my page, an error message is displayed within a div with the class 'validation-errors'. I'm looking for a solution to trigger a javascript function (which adds a CSS property to a ...