I would like to know how are require('/file.json')
, reafFile('/file.json', callback)
and readFileSync('/file.json', 'utf-8')
different from each other, and also when to use each.
The reason why I want to know this is because I want to send a file from node.js to angular.js, I've used the three ways and i've noticed that require
parses the file, is the shortest way to get done what i want, in both readFile
and readFileSync
i have to parse the file.
A) require('/file.json')
To use this way we only have to do the following:
var client_content = require( './client/content.json' );
app.get( '/api/v1/content', function ( request, response ) {
response.setHeader( 'Content-Type', 'application/json' );
response.json( client_content );
} );
B) reafFile('/file.json', callback)
In this case we have to parse the file
app.get( '/api/v1/content', function ( request, response ) {
response.setHeader( 'Content-Type', 'application/json' );
readJSONFile( './client/content.json', function ( err, json ) {
if ( err ) {
throw err;
}
return response.json( json );
} );
} );
function readJSONFile( filename, callback ) {
require( "fs" ).readFile( filename, function ( err, data ) {
if ( err ) {
callback( err );
return;
}
try {
callback( null, JSON.parse( data ) );
} catch ( exception ) {
callback( exception );
}
} );
}
C) readFileSync('/file.json', 'utf-8')
We have to parse the file too
app.get( '/content', function ( request, response ) {
response.json(JSON.parse(require('fs').readFileSync('./client/content.json', 'utf8')));
}
So, what way is better and when is better to use each of them?, what are the differences between them?