Next.js is throwing a TypeError because it does not recognize the function fs.readFileSync

In my JSON data file called total.json, I store information for a chatbot.

{ "guilds": 3, "users": 21 }

Within my index.tsx file, I want to display this data on the webpage, so I attempt the following:

import fs from 'fs';

function displayStats() {
  const botStats = JSON.parse(fs.readFileSync(`../util/total.json`, { encoding: 'utf8' }));
  const usersCount = botStats.users;

  console.log(usersCount);
  return usersCount;
}

Although the function correctly outputs the number (21) in the terminal, an error is encountered when trying to display it on the page:

TypeError: fs__WEBPACK_IMPORTED_MODULE_6___default(...).readFileSync is not a function

Answer №1

When working in Node.js, you can utilize the fs module but keep in mind it is not compatible with browsers. If you need to access JSON data from a file within Next.js, options include using axios or fetch. Below is an example showcasing the usage of axios:

import axios from 'axios';

  async function stats() {
    var {data} = await axios.get("http://localhost:8888/utils/total.json");//Modify this URL accordingly
    const botcount = JSON.parse(data)
    const userscount = botcount.users;

    console.log(userscount);
    return userscount;
  }

Answer №2

As previously mentioned by @JaivBhup, using fs is not compatible with browsers.

In my opinion, a better approach would be to utilize a backend to fetch data (consider using the axios package for this). If you do not have a backend setup, you can explore using the Next.js api routes.

You can work with it just like you would with Node.js!

Check out the official documentation or refer to this article for further insights.

// File: pages/api/my-json.js

import fs from 'fs'
import path from 'path'

export default (req, res) => {
  // Assuming your json file is located at /public/assets/my-json.json
  const filePath = path.resolve('./public', 'assets', 'my-json.json');
  const json = fs.readFileSync(filePath);

  res.statusCode = 200
  res.json(json);
}

The key part here is path.resolve(...), which tells vercel to include the specified path in the serverless lambda function. This code snippet enables reading images and other files from both local and remote locations on vercel!

I made a slight modification to load the json file instead of file names.

Answer №3

To successfully read a file in Node.js, you can utilize the following code:

import { promises as fs } from "fs";

Additionally, ensure to use the await keyword when reading the JSON content:

const botcount = await fs.readFile(../util/total.json, 'utf8' ));

This method will allow you to read the file content asynchronously.

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

Jest snapshot tests using react-test-renderer encounter null references in refs

Having an issue with manually initializing the Quill editor in componentDidMount and encountering Jest test failures. It seems that the ref value I am receiving is null in jsdom. There is a related issue here: https://github.com/facebook/react/issues/7371, ...

Using regex to confirm prices are accurate

Can anyone assist me with validating input using regEx in Vue? I'm struggling to create one and haven't been able to find the correct pattern online for what I need. The specific validation I am attempting is for a price value that should be a f ...

Reducing the slide margins in impress.js?

When using Impress.js, I noticed that the default slides have a large left margin (or padding - it's hard to determine with Firefox's Inspector). I have a slide with a wide <pre> block that would fit if it were aligned to the left, but it d ...

Do JavaScript Promises operate asynchronously?

Can we clarify if JavaScript Promise is asynchronous? I've been researching Promise and async programming, particularly with ajax requests. If Promise isn't inherently async, how can we make it so? For instance, consider a function that encapsul ...

Utilizing Laravel's URL::asset method in conjunction with a JavaScript variable

Having a go at creating an HTML tag using the Jquery snippet below $("<option />",{ 'data-src':"{{ asset(my-javascript-variable) }}", id:'my_id').appendTo($('#image')); An option tag is being added to a select element. ...

Utilize Nuxt.js context within a Vue plugin

I have a situation where I'm working with Nuxt.js and have two plugins set up. In order to gain access to the VueI18n instance from lang.js within validate.js, I am in need of some guidance. Is there anyone familiar with how this can be accomplished? ...

What is the process for including an item in an array within Firestore?

Can someone help me with this code snippet I'm working on: await firebase.firestore().doc(`documents/${documentData.id}`).update({ predictionHistory: firebase.firestore.FieldValue.arrayUnion(...[predictions]) }); The predictions variable is an ar ...

Improve code efficiency by streamlining a function and using more effective syntax techniques

I've been learning how to condense code with jQuery. Can this script be written in a more concise manner without everything being on one long line? items.push('<li id="' + key + '">' + ' (key: ' + key + ')&apo ...

Performing CRUD operations with mongoose and express

My express app is currently being developed with mongoose, and the goal is to integrate it with React for the front end. In my customer controller, I have outlined some CRUD operations, but there are aspects of this approach that I find unsatisfactory. W ...

Display a pop-up window when hovering over a table cell using HTML and JavaScript

I am currently developing a JavaScript application and came across a helpful library called qtip2. My objective is to have different information displayed when the user hovers over each cell in the table. The qtip2 library I mentioned earlier can display ...

Having multiple upload forms on a single page with PHP, AJAX, and jQuery is not functioning as expected

I'm on the hunt for a jQuery-AJAX image uploader that supports multiple instances of the form on a single page. Do you have any recommendations? Here's my scenario: I have a front-end page where users can update their profiles. Upon loading the ...

Incorporating traditional Bootstrap styling directly into a React application without relying on the react-bootstrap library

My goal is to incorporate my existing bootstrap components into a React project without having to rewrite them to work with the react-bootstrap library. While I have successfully integrated the bootstrap CSS, I am facing issues with the functionality aspec ...

Developing a dynamic slideshow using jQuery

I'm working on a website where I want an image to change when I click on a specific piece of text. Currently, I have set up a class called "device" with one of them having the class "active" like this: <div class="col-md-3"> <div c ...

"Steady layout of grid for the navigation bar and

Currently, I am in the process of developing a control panel with the use of HTML and CSS. To structure the page, I opted for a grid layout. However, I encountered an issue where the navbar and sidebar do not stay fixed on the screen despite trying various ...

Ways to combine X and Y velocities into a single velocity

Is there a way to combine the X and Y Velocity into a single Velocity without considering the angle? var velocityX = some value; var velocityY = some value; // Need to convert both X and Y velocities into one combined velocity ...

Explore the power of Infinity.js for optimizing the rendering of large HTML tables, complete with a detailed example using prototype

Is there a way to efficiently load/render large html tables without compromising performance, especially in Internet Explorer? I recently came across a plugin in prototype.js (https://github.com/jbrantly/bigtable/, post: , demo:) that addresses this issue ...

Preventing the addition of duplicate items to an array

My current challenge involves pushing containers into an array in my JavaScript code. However, once a container has been pushed, I want to prevent that same one from being pushed again. If you'd like to take a look at the JSfiddle where I'm work ...

Is there a way to automatically refresh a page as soon as it is accessed?

My goal is to create a page refresh effect (similar to pressing Command+R on Mac OS) when navigating to a certain page. For instance: Currently, when I navigate from "abc.com/login" to "abc.com/dashboard" after successfully logging in, the transition occ ...

Utilizing fluent-ffmpeg in nodejs and express to effortlessly download a video

I've been recently tackling a side project that involves downloading videos from Reddit. The tricky part is that the video and audio are stored in separate files, requiring me to merge them before being able to download them onto the client's dev ...

A guide on transferring a Vue component to a custom local library

After successfully creating components using template syntax (*vue files), I decided to move common components to a library. The component from the library (common/src/component/VButton): <template> <button ... </button> </templat ...