How to run a NodeJS file from a url request - javascript

I want to run a NodeJS file index.js from url request, whenever I hit this url like localhost:8080 it automatically run the index.js file.

I'm not exactly sure what you are trying to do, but maybe something simple like this?
var yourSuperAwesomeAPI = require('./yourSuperAwesomeAPI.js');
var http = require('http');
http.createServer(function (req, res) {
switch(req.url){
case '/': res.write('website.com'); break;
case '/about_us': res.write('website.com/about_us'); break;
case '/api':
yourSuperAwesomeAPI();
break;
default: res.write('website.com/error_404');
}
res.end();
}).listen(8080);
You can just run it like that. You could also get the url parameters, so you can take input, so you may want to check out the url module for nodejs or you can just google how to get url parameters.
As I said i'm not sure if this is what you want to do, if you want to just return a .js file that is a bit different, but generally pretty similar.

You could use child process module of nodejs to execute any shell commands or scripts within nodejs.
Create an executable bash file like:
myProcess.sh >
node <path-to-file>/index.js
And at your URL handler you can initiate the call like below:
const exec = require('child_process').exec;
var yourscript = exec('sh myProcess.sh',
(error, stdout, stderr) => {
if (error !== null) {
console.log(`exec error: ${error}`);
}
}
)

Related

html page not loading when running javascript server

So I'm creating a game with HTML, css, and javascript, and I'm trying to incorporate template engines/ajax in this task. I made a server which if I run in cmd and then open up google chrome and type 'localhost:3000' in the address line, it is supposed to direct me to the main.html page.
However, when I type 'node server.js' in cmd, it runs properly but when I enter 'localhost:3000' in the browser it says the page does not exist. I'm not sure what went wrong. If I were to manually double click on the html file in my folder, it works, but I'm trying to get it to load by running a server.
I have three folders (img, node_modules, and pages) and 2 json packages which were created by installing express and pug. It's hard to explain my folder paths and code here, so I have a link to a folder containing my files/sub folders and it also gives a clearer view of the path in my directory: https://github.com/jessaisreal/game
It wouldn't let me upload the node_modules folder as it was too big, but I automatically got it from typing 'npm init', 'npm install express' and 'npm install pug' into the cmd line in the folder.
I'm assuming something is wrong with my server.js file or the way my folders are set up. I'm really desperate to get my program working and would appreciate any help. I have no idea why my html page isn't loading. I'm also not sure if I handled the GET request for getting specific fonts correctly.
I cut down my program as much as I could. There are several html and css files, but only included create and main here for simplicity. Again, I would appreciate any help or a push in the right direction!!
server.js:
const http = require('http');
const fs = require("fs");
const pug = require("pug");
//user pug functrion to render through the create Page
const renderMain = pug.compileFile('pages/main.pug');
const renderCreate = pug.compileFile('pages/create.pug');
//Helper function to send a 404 error
function send404(response){
response.statusCode = 404;
response.write("Unknown resource.");
response.end();
}
// Helper function to send 500 server error;
function send500(response){
response.statusCode = 500;
response.write("Server error.");
response.end();
}
// initilize the server
const server = http.createServer(function (request, response) {
//console.log(request.method+" -> "+request.url); test about the income request
// handle the get request
if(request.method === "GET"){
if(request.url === "/" || request.url === "/main"){
let data = renderHome("./pages/main.pug",{})
response.statusCode = 200;
response.end(data);
}else if(request.url === "/main.js"){
//read main.js file and send it back
fs.readFile("main.js", function(err, data){
if(err){
send500(response);
return;
}
response.statusCode = 200;
response.setHeader("Content-Type", "application/javascript");
response.write(data);
response.end();
});
}else if(request.url === "/main.css"){
//read css file
fs.readFile("main.css", function(err, data){
if(err){
send500(response);
return;
}
response.statusCode = 200;
response.setHeader("Content-Type", "text/css");
response.write(data);
response.end();
});
}else{
send404(response);
return;
}
}
});
//Server listens on port 3000
server.listen(3000);
console.log('Server running at http://127.0.0.1:3000/');
I highly suggest that you use expressjs for better organizing your project and this issue will be gone

NodeJS Error: Can't Find Variable: require

I am working with a NodeJS server that hosts a website and a Javascript program. Most of the javascript works fine, but I am running into an error now with one of the npm modules that isn't able to be "required".
I'm getting an error from the inspector console that:
ReferenceError: Can't find variable: require
I am not sure what's happening here, as from what I can tell the server should have access to these public modules. Here is the server code:
var fs = require('fs');
var http = require('http');
http.createServer(function(request, response) {
if(request.url === "/Users/christophermartone/Desktop/Programing/resturauntApp/driver.js") {
var file = fs.createReadStream('driver.js');
file.pipe(response);
console.log("Made it to JS");
response.writeHead(200, {'Content-Type': 'text/javascript'});
}
else {
var file = fs.createReadStream('index.V1.0.html');
console.log("Made it to HTML");
file.pipe(response);
response.writeHead(200, {'Content-Type': 'text/html'});
}
}).listen(8080);
I found some documentation that suggested I should do npm link #Source/Module... which I did, but the issue is still not resolved.
Am I missing something in the server script? Or is there an extra step I am missing?
I can provide the full html and javascript code if needed, but the issue does not appear to be with them, only when they are running on the Node server.

How to call node.js server javascript from html page

Situation
I have a html page which calls multiple javascript files. Everything works on client-side right now.
Because I need to execute a jar within javascript, I am switching to Node.js. (applets are deprecated)
However, I am new to node.js and confused about how to link everything.
I have :
index.html which calls various .js scripts (files.js,objects.js,etc.)
webServer.js which makes the node.js server
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8080);
javaApp.js which executes a jar
var exec = require('child_process').exec;
var child = exec('java -jar E:/JavaApp.jar',
function (error, stdout, stderr){
console.log('Output -> ' + stdout);
if(error !== null){
console.log("Error -> "+error);
}
});
module.exports = child;
The question
I would like, when clicking on a button in my html, to call javaApp.js on the server side.
I know Express can be used to link index.html to webServer.js, but I don't understand how to link index.html to the code used by the server.
i.e. How can I call javaApp.js from index.html if there's no function name in it?
Is this answer relevant ? How to call node.js server side method from javascript?
If you want to call the jar on the server you have to create a route for it(maybe using express).
router.get('/call-java-app', function (req, res, next){
//call you function in here
//respond with any data you want
res.send('Your data here');
});
Your button would have to make a get request at /call-java-app and optionally wait for any response from the server.
var url = '/call-java-app';
console.log(url);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState === 4) {
//handle server response here if you want to
}
}
xmlHttp.open("GET", url, true); // false for synchronous request
xmlHttp.send(null);
How can I call javaApp.js from index.html if there's no function name in it?
You can't. At least not sensibly.
Change it so it exports a function you can call if you want to call it multiple times.
Since it is asynchronous, you should make that function return a Promise.
In your webserver, require the module you write to get access to the function it exports.
Write a route which calls that function and returns a suitable HTTP response.
Then cause the browser to make an HTTP request to that route by clicking a link, submitting a form, using fetch, or whatever other method you like.
Your webserver is now as simple as it (almost) can be. Just sending index.html when the ip+port 8080 is called with http (get).
Before you can use your jar-module you have to make a requiere in your webserver:
var child = require('javaApp')
This will give you access to "child" wrappet with a error-function. What "child" actual is doing and can do, you probably know (i hope). If you skip the index.html you can send some response from your "child" to see how it works.

NodeJS Error EADDRINUSE and HTML file not rendering, instead shows html codes

I'm new kid on the block with NodeJS. Right now im following a basic tutorial of NodeJS, so far so good.
But I have a problem using fs.createReadStream method:.
var http = require("http");
var fs = require("fs");
function fourOHfour(response) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("four oh four.....");
response.end();
}
function onRequest (request, response) {
if(request.method == 'GET' && request.url == '/'){
response.writeHead(200, {"Content-Type": "text/plain"});
fs.createReadStream("./index.html").pipe(response);
}
else{
fourOHfour(response);
}
}
http.createServer(onRequest).listen(8888);
console.log("server is running......");
When I go on my browser and type localhost:8888, it should be rendering the index.html file in HTML but the result is wrong, all I get is a bunch of codes of index.html file - plain text.
Meanwhile in my sublime compiler, I've got no error in regards to this case. Until i try to edit my code, whatever I cahnge, it will give me an error like this:
If that thing happen, I cant fix the error unless I restart the laptop, then everything running well again. At least my compiler say that the server is running... Even thought my localhost:8888 still not rendering the HTML file.
You are specifying your content type as: text/plain which means the page will not render in HTML but instead, plain text. This is why you see the "codes" from your HTML file instead of the actual HTML being rendered.
To fix that problem, set the content type to text/html like so:
response.writeHeader(200, {"Content-Type": "text/html"});
In regards to the error you posted, "EADDRINUSE"
EADDRINUSE means that the port number which listen() tries to bind the server to is already in use.
So, in your case, there must be running a server on port 8888 already.
Check for the listening event like this, to see if the server is really listening:
var http=require('http');
var server=http.createServer(function(req,res){
res.end('test');
});
server.on('listening',function(){
console.log('ok, server is running');
});
server.listen(8888);
EADDRINUSE - seems like port is busy by another process or maybe by same nodejs process that don't want to close.
try to kill process:
killall node
about code - try this:
var http = require("http"),
fs = require("fs"),
URL = require('url');
function output(response, body, status) {
status = status || 200;
response.writeHead(status, {"Content-Type": "text/html"});
response.end(body);
}
function fourOHfour(response) {
output(response, 404, "four oh four...");
}
function onRequest (request, response) {
var uri = URL.parse(request.url).pathname; // extractin URI part
var method = request.method || 'GET'; // detecting method otherwise GET
if(method == 'GET' && uri == '/'){
// reading file
fs.readFile(__dirname+'/index.html', function(err, data) {
if(err) { // if error happen, output error
output(response, err, 500);
return;
}
output(response, data); // ouput html body
});
return;
}
fourOHfour(response);
}
var httpServer = http.createServer();
httpServer.on('request', onRequest);
httpServer.listen(8888);
To run Your code in production do following in terminal:
install forever:
sudo npm install -g forever # remove sudo word if You use windows, or You're already root user
start app using forever:
forever start app.js
To run Your code in development environment:
install nodemon:
sudo npm install -g nodemon # remove sudo word if You use windows, or You're already root user
run Your app using nodemon:
nodemon app.js
Forever will keep Your app running and will output logs which You can see using:
forever list # lists running processes
forever logs # shows logs that outputs forever
forever logs 0 # read logs of 0-th process
To restart forever process:
forever restartall # restarts all forever instances
forever restart 0 # restarts first process
To stop:
forever stopall
forever stop 0
About Nodemon: it's a tool that watches changes in Your file and restarts it automatically, no need to stop-start Your app, so that's why I prefer nodemon in dev environment

Node.js - Loading Files in Runtime

I'm fairly new to Node.js and am having trouble understanding the way to go about loading libraries or files, in runtime.
Apparently, it is a bad idea to load files in runtime using Node.js's native "require" function because it is blocking i/o, and therefore should not be used from within request handlers. So, I'm assuming something like this is to be avoided:
var http = require('http').createServer(function(req, res) {
var file = require('./pages/'+req.url);
res.end();
}).listen(8080);
So then is there a way to require files in runtime, in a non-blocking/asynchronous way?
I don't think it would always be possible to load files in "boot time" rather than runtime because like in the example above, the only way to know what file to load/require is by getting the name through the req.url property.
So that seems like the only option. Unless, all the files in the folder are preloaded and then called upon by name, in the callback (By using fs.readdirSync or something to iterate through all the files in the folder and compare the gotten files' names to the req.url property), but that seems wasteful. "Preloading" all the files in the folder (maybe around 50 files) and then only using 1 of them, doesn't seem like a good idea. Am I wrong?
Either way, I would just like to know if there is a way to require files in runtime in a better, non-blocking/asynchronous way.
Thank you!
The function require() is generally used for caching modules or configuration files before most of your application runs. You can think of using require() somewhat like this:
var file = fs.readFileSync('/path');
// depending on the file type
eval(file);
JSON.parse(file);
The reason it is done this way is so that dependencies are loaded in order. If you want to read a file after initializing the application, you should use a asynchronous read, and respond in the callback like this:
var http = require('http');
http.createServer(function(req, res) {
fs.readFile('./pages/' + req.url, function(err, data) {
res.end(data);
});
}).listen(8080);
If you needed to check if a file existed, then you could use fs.stat() to check the existence of a file, rather than querying the directory.
var http = require('http');
http.createServer(function(req, res) {
var file = './pages/' + req.url;
fs.stat(file, (err, stats) {
if (err || !stats.isFile()) {
res.writeHead(404);
res.send();
return;
}
fs.readFile(file, function(err, data) {
res.writeHead(200);
res.end(data);
});
});
}).listen(8080);

Categories

Resources