fs.readFileSync is not a function Meteor, React

后端 未结 3 2084
栀梦
栀梦 2020-12-18 05:31

I\'m getting a \'fs.readFileSync is not a function\' in Chrome debugger after trying to call readFileSync();

I call it...

const fs = require(\'fs\')         


        
相关标签:
3条回答
  • 2020-12-18 05:58

    Thanks for all the answers!

    I have confirmed that you cannot use fs on the client side.

    Instead, I made another local simple express node api and the react web app just makes a request back to the node api to get that data.

    Also, you have to do this...

    https://enable-cors.org/server_expressjs.html

    EDIT:

    Wrote this a long time ago. 3 years back when I was just starting my web development learning. Just want to update and say that there is a serious fundamental difference between what the user sees and what the server sees. Allowing the front-end (Meteor, React, Angular, etc.) to read files would be a super serious security issue. Anyone could make a website that when a user goes to it, it would just read your local computers files. Not good...

    While this is super obvious to me now, it wasn't obvious 3 years ago. So for all you newbies out there, it's okay :) No question is a dumb question.

    0 讨论(0)
  • 2020-12-18 06:00

    fs cannot be used on the client, due to browsers restricting some javascript code.

    If your code is being run on both the server and client, you can use:

    if (Meteor.isClient) return;
    

    to avoid the error. Otherwise, there should be another way to do what you're trying to accomplish, such as importing required JSON.

    0 讨论(0)
  • 2020-12-18 06:04

    I'm getting a 'fs.readFileSync is not a function' in Chrome debugger after trying to call readFileSync();

    fs will not work in the browser. This is by design as to protect your filesystem from potential security threats.

    Using low level Node packages in a browser environment

    If you need access to this in a browser environment, consider making use of Electron which allows you to make use of OS level NodeJS packages in a running instance of Chromium.

    0 讨论(0)
提交回复
热议问题