read-file-utf8

shortcut to fs.readFile or fs.readFileSync

API | Usage | Example | See also | License

API

readFile(filePath[, callback])

Usage

Given a callback to execute on data, for instance

function callback (err, data) {
  if (err) throw err
  console.log(data)
}

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')

Example

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

SELECT COUNT(*) AS num
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)

    console.log(result.rows[0].num)
  })
})

See also

License

MIT