1
0
Fork 0
cosmic-web/utils.js

56 lines
1.2 KiB
JavaScript
Raw Normal View History

2021-06-18 15:03:02 +00:00
var fs = require('fs')
const readline = require('readline')
const { once } = require('events')
var exec = require('child_process').exec
function bufferFile(path) {
2021-06-18 17:29:36 +00:00
try {
return fs.readFileSync(path, { encoding: 'utf8' })
} catch (_e) {
2021-06-18 17:29:36 +00:00
return ''
}
2021-06-18 15:03:02 +00:00
}
async function head (path, lines) {
2021-06-18 15:03:02 +00:00
let x = 0
const acc = []
2021-06-18 15:03:02 +00:00
const readInterface = readline.createInterface({
input: fs.createReadStream(path),
terminal: false,
crlfDelay: Infinity
})
readInterface.on('line', function(line) {
acc.push(line)
x++
if (lines && x >= lines) {
2021-06-18 15:03:02 +00:00
readInterface.close()
readInterface.removeAllListeners()
}
})
await once(readInterface, 'close')
return acc
}
function wc (path) {
return new Promise((resolve, reject) => {
exec("sed -n '$=' " + path, function (error, results) {
if (error) {
reject(error)
} else {
resolve(results.toString().trim())
}
})
})
}
function escape (text) {
2023-01-22 15:50:09 +00:00
return text.replace(/\&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;')
}
2021-06-18 15:03:02 +00:00
module.exports = {
bufferFile: bufferFile,
head: head,
wc: wc,
escape: escape
2021-06-18 15:03:02 +00:00
}