Node js stream file content and stop reading - javascript

I need to stream a log file to my frontend from node js backend and when the user leaves the page stops reading file, I was able to stream ok with tail-stream module and with require('child_process').spawn running tail -f command, but the backend remains running after leaving the page.
What can I do to stop the backend script that keeps watching the file?
here is an example that works as I said before.
var sys = require('sys')
var spawn = require('child_process').spawn;
var filename = process.argv[2];
if (!filename)
return sys.puts("Usage: node <server.js> <filename>");
var tail = spawn("tail", ["-f", filename]);
http = require('http');
http.createServer(function (req, res) {
sys.puts("new connection..");
res.writeHead(200, {'Content-Type': "text/plain;charset=UTF-8"});
tail.stdout.on("data", function (data) {
console.log(new Date());
res.write(data);
});
}).listen(3000);
Thanks in advance.

Related

Can't serve javascript file with html - node.js

I have a webpage with an HTML, CSS, and JS file. It also has one image. I am able to get all of them to function and serve onto the client side, except for the javascript portion. It is most likely a silly syntax thing but I have not been able to solve it.
Here is the code for my .js serving:
else if(req.url === '/index.js'){
console.log("SERVING JS")
res.writeHead(200, {'Content-Type': 'application/json'})
var javaContents = fs.readFileSync('./public/index.js', {encoding: 'UTF8'});
res.write(javaContents);
res.end();
}
^^^ Which is inside my requestHandler function:
function requestHandler(req, res){
}
Before this, I also have:
var http = require('http'), fs = require('fs');
var fs = require('fs');
And I declare my server variable last:
var server = http.createServer(requestHandler);
server.listen(9934, function(){
console.log("== Server is listening on port 9934");
});
I could post all my code but I think that is not necessary. Thank you!

Loading html page on nodeJS won't load until keyboard interrupt

I am new to nodeJS. I am trying to load an index.html page onto my 8080 port and have this:
var http = require('http');
var fs = require('fs');
var PORT = 8080;
function home(req, res) {
if(req.url == '/'){
fs.readFile('index.html', function read (err, data) {
res.writeHead(200, {'Content-type' : 'text/html'});
res.write(data);
res.end();
});
}
};
var server = http.createServer(function (req, res) {
home(req, res);
});
server.listen(PORT);
I have 3 files in the same directory: index.html, style.css, server.js. I start up the server and the page will not load until after I hit cntrl + c. Why is this?
You have written the data to the response, but you have not finished the response. Put res.end(); after your res.write function.
Without this, the browser keeps waiting for more data from the server. When you shut down the server with Ctrl-C, the server closes the connection, and the browser renders what it received.
If you are new to Node, I would recommend looking into something like Express, which handles a lot of important things like routing (what URLs go to which pages) for you and will save you a lot more if statements in the future.

Nodejs App doesnt spawn python child process when Nodejs app started using Systemd

I'd like to start my node js application on boot. Therefore I start a service from Systemd:
[Unit]
Description=Node.js server
After=network.target
[Service]
ExecStart=/usr/bin/node /var/www/Raspberry-Pi-Status/js/server.js
Restart = always
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=nodejs-server
Environment=NODE_ENV=production PORT=8000
Environment=PYTHONPATH=/usr/bin/python
[INSTALL]
WantedBy=multi-user.target
The server.js looks like this:
var util = require('util'),
spawn = require('child_process').spawn,
py = spawn('python',['temperature.py'],{detached: true});
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'monitor',
password : 'password',
database : 'temps'});
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
sys = require('util'),
exec = require('child_process').exec,
child;
// Listen on port 8000
app.listen(8000);
// If all goes well when you open the browser, load the index.html file
function handler(req, res) {
fs.readFile(__dirname+'/../index.html', function(err, data) {
if (err) {
// If no error, send an error message 500
console.log(err);
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
py.stdout.on('data', function(data){
console.log('testing');
date = new Date().getTime();
temp = parseFloat(data);
io.sockets.emit('temperatureUpdate',date,temp);
});
// When we open the browser establish a connection to socket.io.
// Every 5 seconds to send the graph a new value.
io.sockets.on('connection', function(socket) {
console.log('user connected');
});
The node.js application should start a python script which reads out a temperature sensor. When I start node.js via the console everything works fine. However, when I start from Systemd, the python script is not spawned.
What's the problem there? Am I missing something?
Thanks in advance
Alexander
An issue could be the difference in the current working directory when run manually vs systemd. The spawn call used is documented has a default to inherit the current working directory.
When run via the shell, that would be whatever directory you are currently in. In man systemd.exec, you find the "WorkingDirectory=` directive, which documents systemd's default current working directory: "defaults to the root directory when systemd is running as a system instance".
So if your temperature.py is located in /var/www/Raspberry-Pi-Status, then set:
workingDirectory=/var/www/Raspberry-Pi-Status in your `[Service]` section.

Node.js - update server page

After create the http server and listen to it:
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write("<!DOCTYPE "html">");
response.write("<html>");
response.write("<head>");
response.write("<title>Hello World</title>");
response.write("</head>");
response.write("<body>");
response.write("Hello World!");
response.write("</body>");
response.write("</html>");
response.end();
});
server.listen(1337);
now I want to update the page but don't want to exit() the server. How can I do it?
Use Nodemon, it is a utility that will monitor for any changes in your source files and automatically restart your server.
Steps:
Install nodemon globally npm install nodemon -g
Run the server nodemon app.js
This way you do not have to exit the server everytime you update the page/server logic.
As #Pavol Pitonak suggested, you should use multiple files, one for node server boot, second for index page, so when you edit your index.html file - server doesn't need restart.
server.js file
var http = require('http');
var path = require('path');
var fs = require('fs');
var server = http.createServer(function(req, res){
// get path to file we gonna send
var indexFilePath = path.join(__dirname, 'index.html');
// read file contents
fs.readFile(indexFilePath, function(err, contents){
if(err){
// for debugging
console.log(err);
} else {
// send file content
res.end(contents);
}
});
});
server.listen(1337);
index.html file
<!DOCTYPE html>
<html>
<body>
Hello world
</body>
</html>

Node.js how to keep on reading a text file

I'm trying to read a text file. The text file is updated everytime an event occurs in my c program in linux.
Here's my code.
var http = require('http'),
fs = require('fs');
var filetoread = fs.readFileSync('this_is_a_log.txt');
server = http.createServer();
server.on('request', function(req, res){
res.writeHead(200, {'content-type': 'text/html'});
res.end(filetoread);
});
server.listen(9000);
How can node.js continue reading the text file so the page keeps updated everytime the text file is modified. I don't want to use a delay or timeout, I want to do it real time. Is there a function in node.js that can do this. Also I don't want to use tail.

Categories

Resources