title: Change text file when Raspberry Pi loses power
body: <p>I'm writing a small application for my Raspberry Pi to surveil my surroundings and I want to know when the Raspberry Pi loses power using NodeJs.</p>
  
  <p>I've found that you can use a signal that the Pi send, <code>SIGPWR</code>, when it loses power.</p>
  
  <p>I made this little test script:</p>
  
  <pre><code>// test.js
  var fs = require('fs');
  var path = '/home/pi/Documents/Code/surveillanceCam/log/logfile.txt';
  
  fs.writeFileSync(path, new Date().toString() + ': Start\n');
  
  process.on('exit', function () {
      fs.appendFileSync(path, new Date().toString() + ': exit\n');
  });
  
  process.on('SIGPWR', function () {
      fs.appendFileSync(path, new Date().toString() + ': SIGPWR\n');
  });
  
  process.stdin.resume();
  </code></pre>
  
  <p>If I run the script with <code>node test.js</code> I get a line in <code>logfile.txt</code> that end with Start so that works, and if I remove the last line (so the scripts don't run until I stop it), I also get a new line with exit in the end.</p>
  
  <p>But if I keep the last line so the script keeps on running, and then I pull the cable of the Pi, then insert it again. When I go to watch the file after it boots I only get the line with the start in the end..</p>
  
  <p>I want to have 2 lines in my <code>logfile.txt</code> one with the time of start, and one with the time of power loss..</p>
  
  <p>And from what I've read the <code>SIGPWR</code> signal is sent when power is lost. Does the script not have enough time to write to the file or is there something else I can do?</p>
  
  <p><strong>EDIT:</strong> What I want to do is to simulate a power loss and when the power is lost write to the file.</p>
  
  <p><strong>EDIT2:</strong> I think how I will solve this problem is to add a <code>process.on('SIGINT',...)</code> signal. So when the user ends the program with Ctrl+C I will then and only then write to the file. And then when the node server start I will check if there is something in the file. If there isn't then the node server didn't shut of gracefully and I should display an error.</p>