Scan a directory

var path = require('path');
var fs = require('fs');

var dirPath = path.join(__dirname, 'files');

fs.readdir(dirPath, function (err, files) {
    if (err) {
        return console.log('Unable to scan dir ' + err);
    files.forEach(function (file) {
        // Do something with the file.

Node js write to file

When using file systems writeFile function, a new file is created when the writeFile method is executed.

var path = require('path');
var fs = require('fs');

var filePath = path.join(__dirname, 'files', 'test.txt');

fs.writeFile(filePath, 'Write text to file, overwrite all.', function(err) {
    if(err) {
        return console.log('Unable to write file ' + err);
    console.log('File was saved');

Node js read file

Path.join is used to create the file path. There is a directory "files" in the root of the project, where a "test.csv" file is stored. We handle file reading asynchronous.

Work with terminal input

var readline = require('readline');

 * We need to create a readline interface.
 * The interface takes 2 streams.
 * The input field points to the readable input stream
 * and the output field to the writable output stream. 
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout

rl.question('Please tell me your name: ', function (name) {
    rl.question('Hello ' + name + ' how old are you: ', function (age) {
        // process.stdout.write('Well hello ' + answer);

Create a package.json file

A package.json file can be created by using the package manager. So it is as simple as typing npm init in the terminal.

npm init

When initializing, some information is given and questions are asked:

Create a form with Jade

Code is put inside a .jade file. These examples were placed inside the index.jade file of an express application.

Add a public directory to express

By convention, images, javascript and css files are stored in a public directory in express. Create a public directory in the root of your project and add 3 directories to it

  • images
  • javascript
  • stylesheets

You can rename the directories, but as the names are commonly used it's better to stick to it.

Create a basic express application

To create a basic express application, the only thing needed is adding a dependency to express in the package.json manifest and run npm install.
A dependency to jade is added, as jade is the view engine of choise for my basic express application.


Subscribe to RSS - Node.js