Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

node.js - fs.writeFile is not working on my ReactJs / NodeJs app

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 |             }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...