node package manager
Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org »



shortcut to fs.readFile or fs.readFileSync

API | Usage | Example | See also | License


readFile(filePath[, callback])

  • @param {String} filePath
  • @param {Function} [callback] optionally passed to fs.readFile
  • @returns {String} content, only if callback is not provided


Given a callback to execute on data, for instance

function callback (err, data) {
  if (err) throw err

then, the following code

var read = require('read-file-utf8')
var filePath = '/tmp/foo'
read(filePath, callback)

actually is the same as

var fs = require('fs')
var filePath = '/tmp/foo'
fs.readFile(filePath, 'utf8', callback)

If no callback is provided, the synchronous version is used, hence the snippet

var content = read('/tmp/bar')

is equivalent to

var content = fs.readFileSync('/tmp/bar', 'utf8')


Suppose you have some SQL queries. It is really better to put every query in its own queryFile.sql, instead then inside someOtherFile.js.

Create a sql/ folder and put there all your queries. Add also a sql/index.js with the following content

var path = require('path')
var read = require('read-file-utf8')
function sql (fileName) {
  return read(path.join(__dirname, `${fileName}.sql`))
module.exports = sql

Suppose there is a sql/count_winners.sql file with the following content

FROM foo.contest
WHERE is_winner IS TRUE

Now you are able to do, for example

var sql = require('./path/to/sql/')
var pg = require('pg')
var conString = 'your connection string here'
pg.connect(conString, function (err, client, done) {
  if (err) return console.error(err)
  client.query(sql('count_winners'), function (err, result) {
    if (err) return console.error(err)

See also