Tag Archives: Files

How to read and write files in Node.js?

To manage files in Node, we use the fs module (a core module). We read and write files using the fs.readFile() and fs.writeFile() methods, respectively.

Steps to read and write files are shown below:

// Include http module,
var http = require(“http”),
fs = require(“fs”);

// Create the http server.

http.createServer(function (request, response) {
// Attach listener on end event.
request.on(‘end’, function () {
// Check if user requests /
if (request.url == ‘/’) {
// Read the file.
fs.readFile(‘test.txt’, ‘utf-8′, function (error, data) {
// Write headers.
response.writeHead(200, {
‘Content-Type': ‘text/plain’
});
// Increment the number obtained from file.
data = parseInt(data) + 1;
// Write incremented number to file.
fs.writeFile(‘test.txt’, data);
// End response with some nice message.
response.end(‘This page was refreshed ‘ + data + ‘ times!’);
});
} else {
// Indicate that requested file was not found.
response.writeHead(404);
// And end request without sending any data.
response.end();
}
});
// Listen on the 8080 port.
}).listen(8080);

This code demonstrates the fs.readFile() and fs.writeFile() methods. Every time the server receives a request, the script reads a number from the file, increments the number, and writes the new number to the file. The fs.readFile()method accepts three arguments: the name of file to read, the expected encoding, and the callback function.

Save this as files.js. Before you run this script, create a file named test.txt in the same directory as files.js.

Run application as $node file.js


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.

 

File Uploads in Node.js

We will use Express Framework  and middleware called “multer”.  This middleware is designed for handling the multipart/form-data.

To install multer write following command:

$ npm install multer

To configure multer add following code in server.js:

app.use(multer({ dest: ‘./uploads/’,
rename: function (fieldname, filename) {
return filename+Date.now();
},
onFileUploadStart: function (file) {
console.log(file.originalname + ‘ is starting …’)
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ‘ uploaded to ‘ + file.path)
done=true;
}
}));

Multer emits event on particular situation such as we used onFileUploadStart which means when file start uploading, this event will be emitted.

As soon as onFileUploadComplete event emitted we have set the variable done to true and use it in our router to determine whether file is uploaded or not.

For handling routes, add following code in server.js:

app.get(‘/’,function(req,res){
res.sendfile(“index.html”);
});

app.post(‘/api/photo’,function(req,res){
if(done==true){
console.log(req.files);
res.end(“File uploaded.”);
}
});

To run server add following in server.js:

app.listen(3000,function(){
console.log(“Working on port 3000″);
});

Now, in your HTML file add following:

<form id = “uploadForm”
enctype = “multipart/form-data”
action = “/api/photo”
method = “post”
>
<input type=”file” name=”userPhoto” />
<input type=”submit” value=”Upload Image” name=”submit”>
</form>

In HTML form you must mention enctype=”multipart/form-data” else multer will not work.

Now run your project :

$ node server.js

And visit localhost:3000 to view running application.

To perform validation on Server end, multer provides limits array parameter. If you want you can perform validation as shown below:

app.use(multer({ dest: ‘./uploads/’,
rename: function (fieldname, filename) {
return filename+Date.now();
},
limits: {
fieldNameSize: 100,
files: 2,
fields: 5
}
}));

Multer provides easy way to upload files in Node.js.


ProsperaSoft offers Node.js development solutions. You can email at info@prosperasoft.com to get in touch with ProsperaSoft Node.js experts and consultants.