JS: Node.js File System Module

1 minute read

Add File System Module:

var fs = require('fs');

Read File

s.readFile()

Example:

  fs.readFile('demofile1.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    res.end();
  });

Create Files

fs.appendFile()
The fs.appendFile() method appends specified content at the end of a file. If the file does not exist, the file will be created:
Example:

var fs = require('fs');

fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
  if (err) throw err;
  console.log('Saved!');
});

fs.open()
The fs.open() method takes a “flag” as the second argument, if the flag is “w” for “writing”, the specified file is opened for writing. If the file does not exist, an empty file is created:
Example:

var fs = require('fs');

fs.open('mynewfile2.txt', 'w', function (err, file) {
  if (err) throw err;
  console.log('Saved!');
});

fs.writeFile()
The fs.writeFile() method replaces the specified file and content if it exists. If the file does not exist, a new file, containing the specified content, will be created:
Example:

var fs = require('fs');

fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) {
  if (err) throw err;
  console.log('Saved!');
});

Update Files

fs.appendFile()
fs.writeFile()

Delete Files

fs.unlink()
Example:

var fs = require('fs');

fs.unlink('mynewfile2.txt', function (err) {
  if (err) throw err;
  console.log('File deleted!');
});

Rename Files

fs.rename()

var fs = require('fs');

fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
  if (err) throw err;
  console.log('File Renamed!');
});

Upload Files

var formidable = require(‘formidable’);
Exapmle:

var http = require('http');
var formidable = require('formidable');
var fs = require('fs');

http.createServer(function (req, res) {
  if (req.url == '/fileupload') {
    //upload file
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.path;
      var newpath = 'C:/Users/Your Name/' + files.filetoupload.name;
      //move file to current folder
      fs.rename(oldpath, newpath, function (err) {
        if (err) throw err;
        //file palce on a temppory folder if without fs.rename()
        res.write('File uploaded and moved!');
        res.end();
      });
 });
  } else {
    //create upload form
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
  }
}).listen(8080);

Resource