Skip to content

Instantly share code, notes, and snippets.

@nkashy1 nkashy1/file-sms-signal.js

Last active Apr 22, 2018
Embed
What would you like to do?
Alert using SMS on file creation
var path = require('path');
var {poll} = require('@nkashy1/pollster');
var {spawnPredicate} = require('@nkashy1/pollster/predicates');
var twilio = require('twilio');
// START fs config
var rawFilepath = process.env.WATCH_FILE;
if (!rawFilepath) {
throw new Error('WATCH_FILE (undefined) should be the path that you want to poll for file existence');
}
var filepath = path.normalize(rawFilepath);
// END fs config
// START twilio config
var twilioAccountSid = process.env.TWILIO_ACCOUNT_SID;
var twilioAuthToken = process.env.TWILIO_AUTH_TOKEN;
var twilioPhoneNumber = process.env.TWILIO_PHONE_NUMBER;
var notificationPhoneNumber = process.env.NOTIFICATION_PHONE_NUMBER;
if (!twilioAccountSid || !twilioAuthToken || !twilioPhoneNumber || !notificationPhoneNumber) {
let message = (
'The following environment variables should be defined:\n' +
`TWILIO_ACCOUNT_SID: ${!!twilioAccountSid}\n` +
`TWILIO_AUTH_TOKEN: ${!!twilioAuthToken}\n` +
`TWILIO_PHONE_NUMBER: ${!!twilioPhoneNumber}` +
`NOTIFICATION_PHONE_NUMBER: ${notificationPhoneNumber}`
);
throw new Error(message);
}
var twilioClient = new twilio(twilioAccountSid, twilioAuthToken);
// END twilio config
function smsSignaller(twilioClient, twilioPhoneNumber, notificationPhoneNumber, message) {
function sendSignal(err) {
if (!!err) {
console.error(err);
process.exit(1);
}
return twilioClient.messages.create({
body: message,
to: notificationPhoneNumber,
from: twilioPhoneNumber
}, function(err, message) {
if (!!err) {
console.error(err);
process.exit(1);
}
console.log(
`Message sent: ${message.sid}`);
process.exit(0);
});
}
return sendSignal;
}
console.log(`Watching for file at ${filepath}...`);
poll(
spawnPredicate(
'cat',
[filepath],
{},
100),
1000,
Infinity,
smsSignaller(
twilioClient,
twilioPhoneNumber,
notificationPhoneNumber,
`File created: ${filepath}`)
);
{
"name": "@nkashy1/file-sms-signaller",
"version": "0.0.1",
"description": "Send an SMS on file creation",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "nkashy1",
"license": "Apache-2.0",
"dependencies": {
"@nkashy1/pollster": "0.0.2",
"twilio": "^3.15.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.