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

Parameterized Azure Cosmos DB Stored Procedure

I am currently learning about Azure Cosmos Db, and I am in the process of developing a simple JavaScript stored procedure that will return a document if a specific Id is provided. However, when I run the stored procedure, I do not receive a "no docs foun ...

encountering a glitch during the electron.js build process with nextjs

When attempting to build Electron.js with Next.js, I keep encountering this persistent error. I have updated my packages and reinstalled node modules multiple times, but I am still unable to resolve it. C:\Users\Himanshu\Desktop\claros& ...

Displaying the information fetched using axios on the screen using node.js

Is there a way to display the information from the input boxes in the image on the screen using node js? ...

Obtain the key's name from the select query

My task is to populate a select element from JSON data, but the challenge lies in the formatting of the JSON where the keys contain important information. I do not have control over how the data is structured. I am attempting to iterate through the JSON a ...

The error message "Unable to find 'encoding'" in NextJS is triggered by the use of try/require in the node_modules folder

Running a NextJS app in typescript with version 13.4.19, utilizing @apollo/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d7e687f7b687f4d392334233e">[email protected]</a> triggers a warning during the build proce ...

The Next.js developer encounters an issue where the build fails due to a ReferenceError on a client component, stating that "window

Just starting out with nextjs, I'm sticking to using only the basic features without diving into any advanced functionalities. During the next build process, I encountered an issue where 6 paths failed because of a ReferenceError: window is not defin ...

What could be causing the span class data to not be retrieved by the getText method

Looking to retrieve the value of a span class called 'spacer-right big project-card-measure-secondary-info' <span class="spacer-right big project-card-measure-secondary-info">1</span> snippet of code: browser.waitForEl ...

What is the best way to set up jest to generate coverage reports for Selenium tests?

I recently made the switch to using jest for testing my JavaScript project after encountering coverage issues with mocha and chai. While my unit tests are providing coverage data, my Selenium tests are not. I've tried various solutions found in outdat ...

Learn the steps to dynamically show a navbar component upon logging in without the need to refresh the page using Angular 12

After logging in successfully, I want to display a navbar on my landing page. Currently, the navbar only shows up if I reload the entire page after logging in. There must be a better way to achieve this without a full page reload. app.component.html <a ...

Tips for implementing multi-language URL routing in a Node.js application

I am seeking guidance on how to handle routing for multi-language URLs in Node.js, Currently, I have the following routes set up where each language generates specific routes as shown below. However, with more than 5 languages, efficiency is becoming a co ...

Vue's keydown event will only fire when elements are in an active state

Encountering a strange issue while attempting to listen for keydown events in Vue.js. The keydown event is attached to a div tag that surrounds the entire visible area: <template> <div class="layout-wrapper" @keydown="handleKey ...

Ways to eliminate excess space in a string using Robot Framework

My Variable : 54, 22 What I desire : 54,22 I attempted the following methods: Executing Javascript code var a = 54, 22;var x = a.split(' ').join('');return x and Executing Javascript code var a = 54, 22;var x = a.replace(/&bso ...

Tips on preventing the opening of a new browser tab by using Ctrl + click

Hey there, I've got a list of products that can be selected using the Ctrl key. $(parentSelector).on("click", function (evnt) { evnt.stopImmediatePropagation(); var item = $(evnt.delegateTarget) ...

Issues arise when attempting to determine the accurate dimensions of a canvas

Looking at my canvas element: <canvas id='arena'></canvas> This Element is set to fill the entire website window. It's contained within a div Element, both of which are set to 100% size. I attempted running this script: var c ...

Issues with triggering the success block in AngularJS and Node.js Express when using $http.get

As a beginner in the world of AngularJS and Node.js, I'm facing an issue with my $http.get method. The problem is that the success callback block does not get executed when the request is successful, whereas the error callback works just fine when the ...

Transform Objects Array from AJAX Response into a Distinct JSON Entity

I am encountering a problem with a sample endpoint that is returning [object Object] for JSON data, and I can't figure out why. Mock API Initially, my code was a bit confusing, but fortunately, I found a clearer solution in another answer. functio ...

What's the reason for not being able to customize classes for a disabled element in Material-UI?

Currently, I am utilizing Material-UI to style my components. However, I am facing challenges when trying to customize the label class for disabled buttons. Despite setting a reference as "&$disabled", it does not yield the desired results. import Rea ...

deleting the current product information during an ajax request

After executing the query provided below, I have $product_list in this code. However, I want to use ajax so that when I click on the button link1, $product_list gets emptied. How can I clear the content within products_list using an ajax call triggered by ...

Why does it seem like only one div is being added?

I am facing an issue with dynamically appending multiple div elements. Despite my efforts, only one div element is showing up on the browser when I try to test the code. I have searched for similar problems but could not find any solutions. Any assistanc ...

Using Angular to retrieve JSON data from a static file

Currently, I am attempting to implement this AngularJS example from a tutorial on Login Tutorial Example. Instead of storing the username and password as simple strings, I am trying to retrieve them from a local file. I understand that this may not be the ...