3

I am trying to write some stuff in a file using reactJS and nodeJs but it doesnt work. Here is my code, is a simple one and i get that fs.writeFile is not a function. I get this error for each function that i use from fs. In node_module i have the folder for fs but inside i only have package.json and a readme. I dont know what to do, i searched online for answers but nothing. Any help would be awesome

import React, { Component } from 'react'

const fs = require('fs');

export default class WriteFile extends Component {

write = () => {
    fs.writeFile("file.txt", "Hey there!", function(err) {
        if(err) {
            return console.log(err);
        }

        console.log("The file was saved!");
    }); 
}

render() {
    return (
    <div>
        <button className='btn btn-info' onClick={this.write}>scria-ti-as</button>
    </div>
    )
 }
}

and the error

TypeError: fs.writeFile is not a function

WriteFile._this.write

D:/js/login_reactjs/src/components/WriteFile.js:8

5 | export default class WriteFile extends Component {

6 | 

7 |     write = () => {

8 |         fs.writeFile("file.txt", "Hey there!", function(err) {

9 |             if(err) {

10 |                 return console.log(err);

11 |             }
4
  • Try import fs from 'fs' instead of const fs = require('fs'); Commented Mar 22, 2019 at 14:25
  • @S.Haviv now i get this error: TypeError: fs__WEBPACK_IMPORTED_MODULE_6___default.a.writeFile is not a function Commented Mar 22, 2019 at 14:29
  • How did you create your react app? using create-react-app command? Commented Mar 22, 2019 at 14:31
  • yes, that way @S.Haviv Commented Mar 22, 2019 at 14:33

2 Answers 2

10

fs will not work in the browser. This is by design. fs has been stubbed out See this ticket

You would have better luck using packages that support browsers like browserify or browserFS

Sign up to request clarification or add additional context in comments.

3 Comments

and what if i have to use some external functions that use file-system?
@Horatiu123456 use browserify or some similar packages.
@Horatiu123456 See this ticket
0

In browser you should use File API to access files - https://www.html5rocks.com/en/tutorials/file/dndfiles/

Also take a look at https://electronjs.org/ It allows you to use nodejs APIs like fs in you "native"-like react app.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.