Search code examples
javascriptangularjsnode.jswritefile

How to correctly call fs.writeFile


I can't figure out how to write on a JSON file. I'm working on a Single Application Page, using mostly AngularJS and Node.js

This is my code:

--index.html--

<script type="text/ng-template" id="pages/Animazione.html">
    ...
    <td><input id="clickMe" type="button" value="clickme" ng-click="doPost()" /></td>

--app.js--

var App = angular.module('myMovie', ['ngRoute']);
...
.when('/Animazione', {
        templateUrl : 'pages/Animazione.html',
        controller  : 'AnimazioneController'}
     )
...
App.controller('AnimazioneController', ['$scope','$http', function($scope, $http) {

                    $http.get('Animazione.json').success(function(response)
                    {
                        $scope.myData=response;
                    })
                    .error(function()
                    { 
                        alert("Si è verificato un errore!"); 
                    });


                    $scope.doPost = function()
                {
                    writeOutputFile({test: 1});
                };


}]);

--index.js-- (Server)

function writeOutputFile(data, success, fail) {
  var fs = require('fs');
  fs.writeFile('auth.json', JSON.stringify(data), function(error) {
    if(error) { 
      console.log('[write output]: ' + err);
        if (fail)
          fail(error);
    } else {
      console.log('[write output]: success');
        if (success)
          success();
    }
  });
}

Is there any call or any function that I'm doing wrong?


Solution

  • As far as I know, you can't call a function directly which in the server via client.

    To do this, define and end point in the server and from client make a call to that end point. Inside the handler for that end point in server call your function to write to file.

    Eg: In server define /writefile endpoint like below (where express is used in server side) Add below contents to index.js

    var express = require('express');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var fs = require('fs');
    var http = require('http');
    var cors = require('cors');
    
    var app = express();
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(cors());
    
    app.post('/writefile', function(req, res) {
        var fileData = req.body.fileContent;
        fs.writeFile('message.txt', fileData , function(err) {
          if (err) {
             res.status(500).jsonp({ error: 'Failed to write file' });
          }
          res.send("File write success");
        });
    });
    
    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      var err = new Error('Not Found');
      err.status = 404;
      next(err);
    });
    
    var port = 3000;
    
    app.set('port', port);
    var server = http.createServer(app);
    
    server.listen(port);
    

    Now your server is running in 3000 port.

    In client:

    $http({
       method: 'POST',
       url: 'http://localhost:3000/writefile', // Assuming your running your node server in local
       data: { "fileContent": {"test": 1} } // Content which needs to be written to the file 'message.txt'
    }).then(function(){
       // Success
    }, 
    function(error) {
       //error handler
       console.error("Error occured::",error);
    });