NodeJS - Working with files

nodejs

How can we handle file upload?

npm install formidable
var formidable = require("formidable"), http = require('http'), sys = require('sys');
var fs = require("fs"); 

http.createServer(function(req, res) {
    if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
        var form = new formidable.IncomingForm();
        form.parse(req, function(err, fields, files) {
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.write('received uploaded:\n\n');
            res.end(sys.inspect({fields: fields, files: files}));
        });
        return;
    }
    // Show the file upload form
    rew.writeHead(200, {'Content-Type': 'text/html'});
    res.end('HTML for the form');
}).listen(80);

How can we display the content of a file?

var fs = require("fs");

function show(response, postData) {
    fs.readFile("/tmp/test.png", "binary", function(error, file) {
        if (error) {
        } else {
            response.writeHead(200, {"Content-Type": "image/png"});
            response.write(file, "binary");
            response.end();
        }
    });
}
var http = require('http'); 
http.request({ hostname: 'example.com' }, function(res) { 
    res.setEncoding('utf8'); 
    res.on('data', function(chunk) { 
        console.log(chunk); 
    });
}).end();
var fs = require('fs');
var path = require('path');
fs.readFile(path.join(__dirname, '/data/customers.csv'), {encoding: 'utf-8'}, function (err, data) {
  if (err) throw err;
  console.log(data);
});
var fs = require('fs');
var path = require('path');
fs.readFile(path.join(__dirname, '/data/customers.csv'), {encoding: 'utf-8'}, function (err, data) {
  if (err) throw err;
  console.log(data);
});

See https://www.airpair.com/javascript/node-js-tutorial

How can we write to file?

var fs = require('fs');
fs.writeFile('message.txt', 'Hello World!', function (err) {
  if (err) throw err;
  console.log('Writing is done.');
});
var fs = require('fs');
fs.writeFile('message.txt', 'Hello World!', function (err) {
  if (err) throw err;
  console.log('Writing is done.');
});

How can we stream?

Streaming data is a term that mean an application processes the data while it’s still receiving it. This is useful for extra large datasets, like video or database migrations. Here’s a basic example on using streams that output the binary file content back:

var fs = require('fs');
fs.createReadStream('./data/customers.csv').pipe(process.stdout);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License