Retrieving data from a file results in receiving blank strings

Struggling to access the data within a directory of files, I've encountered an issue where the data doesn't seem to be read correctly or at all. Even though there is content when opening the files individually, when attempting to examine their contents programmatically, it appears empty. My end goal is to gather all this data into an array.

function retrieveFiles(directory, filesList = []) {
  fs.readdirSync(directory)
    .forEach(file => {
        let content = fs.readFileSync(directory + file, 'utf8');
        console.log(content); // Empty
        const filepath = path.resolve(directory, file);
        const stats = fs.statSync(filepath);
        const isFile = stats.isFile();

        if (isFile) filesList.push(content);
    });
    return filesList;
}

Any assistance on this matter would be greatly appreciated.

Many thanks.

Answer №1

If you encounter the following error message:

EISDIR: illegal operation on a directory, read

then it is advised not to attempt reading directories.

function fetchFiles(directory, filesToFetch = []) {
    fs.readdirSync(directory)
        .forEach(file => {
            const filepath = path.resolve(directory, file);
            const stats = fs.statSync(filepath);
            const isRegularFile = stats.isFile();

            if (isRegularFile) {
                let content = fs.readFileSync(filepath, 'utf8');
                console.log(content); // Content is present
                filesToFetch.push(content);
            }
        });
    return filesToFetch;
}

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

Headers cannot be set once they have already been sent in NodeJS

Here is the code where I authenticate users in a group, push accounts into an array, and save them using a POST request on /addaccount. groupRouter.post('/addaccount', Verify.verifyOrdinaryUser, function(req, res, next) { Groups.findById(req.bod ...

Issue: NG04002 encountered post migration from Angular to Angular Universal

Having recently created a new Angular app and converted it to Angular Universal, I encountered an issue when running the project using npm run dev:ssr. The error displayed in the terminal is as follows: ERROR Error: Uncaught (in promise): Error: NG04002 Er ...

Ways to separate a string based on changing values in Javascript

Given this unmodifiable string: "AAACCDEEB" I am looking to split it into an array whenever the value changes. In this scenario, I would end up with 5 arrays like so: [['A','A','A'], ['C','C'], [ ...

Is it possible for jQuery datepicker to choose a date over a decade in the past?

Recently, I encountered an issue with jQuery-UI's datepicker where it was restricting me to select birthdays only within the last 10 years. This basically meant that users older than 10 years couldn't be accommodated :) I attempted to override t ...

PHP-based user interface queue system

I am in the process of developing a website that enables users to manipulate a webcam by moving it from left to right. Each user will have a one-minute window to control the camera. I plan on implementing a queuing system on the site to ensure that users ...

What is the best way to eliminate leading and trailing spaces from a text input?

I'm currently working on troubleshooting a bug in an AngularJS application that involves multiple forms for submitting data. One of the issues I encountered is that every text box in the forms is allowing and saving leading and trailing white spaces ...

Leveraging Github CI for TypeScript and Jest Testing

My attempts to replicate my local setup into Github CI are not successful. Even simple commands like ls are not working as expected. However, the installation of TypeScript and Jest appears to be successful locally. During the Github CI run, I see a list ...

How to choose between AWS.DynamoDB and AWS.DynamoDB.DocumentClient for your specific use case?

As I delve into learning DynamoDB and the AWS serverless stack, I've noticed that many tutorials recommend using AWS.DynamoDB.DocumentClient. This is exemplified by the following code snippet used to create an item: const dynamodb = new AWS.DynamoDB. ...

Tips on recycling JavaScript files for a node.js API

I'm currently using a collection of JS files for a node.js server-side API. Here are the files: CommonHandler.js Lib1.js Lib2.js Lib3.js Now, I want to reuse these JS files within an ASP.NET application. What's the best way to bundle these f ...

I want to create a feature in Angular where a specific header becomes sticky based on the user's scroll position on the

When working with Angular, I am faced with the challenge of making a panel header sticky based on the user's scroll position on the page. I have identified two potential solutions for achieving this functionality. One involves using pure CSS with pos ...

Tips for clearing a saved password in a browser using Angular.js and Javascript

There is an issue with the password and username fields in my Angular.js login page. When a user clicks on the 'remember me' option in their browser after logging in, the saved username and password are automatically displayed in the respective f ...

Dealing with query strings within routeprovider or exploring alternative solutions

Dealing with query strings such as (index.php?comment=hello) in routeprovider configuration in angularjs can be achieved by following the example below: Example: angular.module('app', ['ngRoute']) .config(function($routeProvider, $loc ...

issue with selecting tabs in jquery

I need help with a problem that is connected to my previous article on CSS, button selection, and HTML tags. You can find the article here. I am not very proficient in JavaScript, so I would appreciate any insights or guidance on how to tackle this issue. ...

Is it possible to modify the appearance or behavior of a button in a React application based on its current state?

I'm looking to customize the color of a button based on different states. For example, if the state is active, the button should appear in red; otherwise it should be blue. Can anyone suggest how this can be achieved in React? Furthermore, I would als ...

Choose all the HTML content that falls within two specific tags

Similar Question: jquery - How to select all content between two tags Let's say there is a sample HTML code as follows: <div> <span> <a>Link</a> </span> <p id="start">Foo</p> <!-- lots of random HTML ...

Utilizing JavaScript to call functions from an ASP.NET code file

I am in need of assistance with integrating a JavaScript-based timeline that requires data from an SQL server. I have already developed the queries and JSON conversions using C#.NET functions within a code file associated with an .aspx page. As a newcomer ...

Displaying properties of a class in Typescript using a default getter: Simplified guide

Here is an interface and a class that I am working with: export interface ISample { propA: string; propB: string; } export class Sample { private props = {} as ISample; public get propA(): string { return this.props.propA; } public se ...

Impressive javascript - extract file from formData and forward it

Presented here is my API handler code. // Retrieve data. const form = formidable({ multiples: true }); form.parse(request, async (err: any, fields: any, files: any) => { if (!drupal) { return response.status(500).send('Empty ...

Encountered a problem while rendering the app: [TypeError: Unable to assign a value to the property 'content' since it is undefined]. Implementing Express with

My experience with res.render is flawless: res.render('main', function(err, html){ // Displays '<html></html>' from 'views/main.html' console.log(html); }); However, the situation changes when it comes to ...

What is the issue with retrieving HTML from an iframe in Internet Explorer when the contents are

Here is the script I used to generate an iframe: Ifrm = document.createElement("IFRAME"); document.body.appendChild(Ifrm); IfrmBod = $(Ifrm).contents().find('body'); IfrmBod.append('<p>Test</p>'); The jQuery function for a ...