User Tools

Site Tools


Sidebar

General

Python Tutorials

WebGL Tutorials

Node.js Tutorials

Node.js in WebStorm


Martin Christen

View Martin Christen's profile on LinkedIn


Twitter

Timeline of @MartinChristen

MartinChristen avatar

RT @snebiker: ‹3DGI 2019› - 4th International Conference on #3D #Geoinformation on 28th of Aug @FHNW with top talks on #AugmentedReality #3…
About 3 hours, 2 mins ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

RT @VictorStinner: Basel in 4 photos: very sunny week, lot of music everywhere, amazing architecture, boat ferry pulled by a cable, people…
About 1 day, 4 hours ago by: Martin Christen (@MartinChristen)

MartinChristen avatar

The team of the FindSolar Code Spint @ #EuroPython at the FHNW Campus Muttenz - open source tool for solar panel cl… https://t.co/0WGf9WBDuH
About 2 days, 9 hours ago by: Martin Christen (@MartinChristen)
node:tutorial05

Node.js Tutorials - Part 0

Node.js Tutorial 5

Reading and writing files is something you can't do in standard JavaScript. In node.js file handling comes with the built in file system module called “fs”. The module is loaded using:

var fs = require('fs');

Writing Files

Writing a whole file can be done with the “writeFile” function. This requires a buffer containing the whole contents of the file. There are two versions of this function: The first version “writeFile” is asynchronous and the second version “writeFileSync” is synchronous.

var data = "Hello World, this is a text...";
var filename = "file.txt";

fs.writeFile(filename, data , function (err) {
  if (err) throw err;
  console.log('Ok. File written...');
});

Reading Files

Reading a whole file can be done with the “readFile” function. There is also a synchronous and an asynchronous version of this function.

var filename = "file.txt";

fs.readFile(filename, function (err, data) {
  if (err) throw err;
  console.log("" + data);
});


node/tutorial05.txt · Last modified: 2013/09/16 22:05 by mchristen