Amit Naik
Amit Naik

Reputation: 121

Not able to write data to a file in Node JS

I want to write text in an already created file in Node Js. Here is what I have done

Upload.html

<form enctype ="multipart/form-data" action ="/file" method ="post">


    MAC Address:<br>
  <input type="text" name="macadd" id="macadd"><br>

  Percentage:<br>
  <input type="text" name="percent" id="percent"><br>



<input type="submit"  value='Submit' id="upload">
<br>

</form>

App.js

app.route('/file').post(function (req,res,next) {

        var macadd =req.body.macadd;
       //var percent =req.body.percent;
        var path ="C:\Proj\doc\data.txt";
        var data ="hello";

        fs.writeFile(path,macadd , function(error) {
            if (error) {
                console.error("write error:  " + error.message);
            } else {
                console.log("Successful Write to " + path);
            }
        });
    });

I want to write the value of 'macadd' into the file data.txt. It is mostly an integer value but when I click on submit, in the file it comes as 'undefined' even though it shows as successful write on the console. Any solutions?

Upvotes: 0

Views: 397

Answers (3)

Amit Naik
Amit Naik

Reputation: 121

I just added 2 slashes between the folders of the path and added the path-resolve package. Something like this:

var path =resolve("C:\\Proj\\doc\\data.txt");

For getting the values of the text box into the file I had to remove the encryption type in the form tag.

<form action ="/file" method ="post">


    MAC Address:<br>
  <input type="text" name="macadd" id="macadd"><br>

  Percentage:<br>
  <input type="text" name="percent" id="percent"><br>



<input type="submit"  value='Submit' id="upload">
<br>

</form>

Upvotes: 1

Matt D. Webb
Matt D. Webb

Reputation: 3314

You can use a node utility like path-resolve to help you here:

path-resolve: https://www.npmjs.com/package/path-resolve

$ npm install path-resolve --save

Then use as follows:

var resolve = require('path-resolve');
var path    = resolve("C:\Proj\doc\data.txt").replace(/\\/g,'/');

Upvotes: 1

rasmeister
rasmeister

Reputation: 1996

You will need to change the way you specify the path:

var path ="C:\Proj\doc\data.txt";

should be:

var path ="C:/Proj/doc/data.txt";

Upvotes: 1

Related Questions