Run function in index.js from script in public folder - javascript

I am trying to run a script in my main index.js file from a script in the public folder. I do not know how to link the two.
I am trying to do this because I need to run file system operations on the server side. I have tried to link the script in the main HTML file, but when I try to run the function, it cannot be found.
my index file:
const express = require('express');
const bodyParser = require('body-parser');
var fs = require("fs");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile('public/index.html');
});
app.listen(3000, () => console.log('server started'));
function test() {
console.log("test");
}
my script in the public folder just has test();
my linking HTML
<script src="script.js"></script>
<script src="../index.js"></script>
I am expecting the test function to run, and log 'test'. It does not, and i get no console logs or errors.
All code is available on repl.it

People say the best feature of Node.JS is the ability to use the same code on the client and the server. However it isn't that simple.
You can't just include code in your HTML outside of the public folder. If you want to call a function on the server side, you will need to do something like this:
app.get('/test', (req, res) => {
test() // will log on the server side
res.send("All ok!");
});
And request that on the client side like so:
fetch('/test').then(res => {
console.log('got result from server!')
})
Essentially, you cannot just call functions on the server side - you have to talk to the server through HTTP. What you can do is create a shared folder with utility functions which you could include on both the client and server, but they couldn't be written with any reference to node modules unless you used a bundler (such as WebPack / RollUp).

you are confused with client side java script and server side node js file.
index.js is server side node js file. It has express link and runs like node index.js now if you want to use a java script function inside node js application you can use this example.
http://techslides.com/client-side-javascript-to-node-js
rest this line cannot be used for a nodejs server side js file.

You cannot run a function in your server script from another script which is running in the browser unless the function is set to be called via an end point. The server script and the browser script are not running in the same system so, they don't share the same execution context to call the functions in each other in a plain fashion.
Here is how you set the server function to be able to call from another system.
app.get('/runtest', (req, res) => {
test();
rest.status(200).send('Ok');
});
Now you can call this from your browser script via ajax.

You can't run a script in public folder in index.js in server-side. Because index.js is a script running in a server. This can't be include script in public folder which runs in the client(web browser). To run script.js in public folder you can create a new file in server with same name scirpt.js.
Script.js
module.exports = function test () {
// do some stuff
};
And import in index.js.
Index.js
const express = require('express');
const bodyParser = require('body-parser');
// import test function from script.js file in here
const test = require('./script.js');
var fs = require("fs");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile('public/index.html');
});
app.listen(3000, () => console.log('server started'));
// using it in here
test();
The const test = require('./script.js'); using to import function test from script.js file and using it in the last line test().

Related

How can i get response from another JavaScript file while working with nodejs and express?

I'm trying to learn nodejs and express and i created a simple server. I want to run some JS code for response.
When I used this method it's works.
const express = require('express');
const path = require('path');
require('dotenv').config();
const app = express();
const port = process.env.PORT || "8000";
app.get('/', (req, res) => {
res.send(`<script>
console.log("Program works!");
</script>`);
});
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`);
});
But writing JS as String is hard so I tried this:
const express = require('express');
const path = require('path');
require('dotenv').config();
const app = express();
const port = process.env.PORT || "8000";
app.get('/', (req, res) => {
res.send(`<script src="./response.js"></script>`);
});
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`);
});
And i get this error:
GET http://localhost:8000/response.js net::ERR_ABORTED 404 (Not Found)
When you send this:
<script src="./response.js"></script>
to the browser, the browser will parse that and see the src attribute and will then immediately request ./response.js from your server. But your server doesn't have any route to respond to that request (thus it gets a 404 error back from your server). Remember that a nodejs server serves NO files by default (unlike some other web servers). So, you have to create routes or middleware for anything that you want it to serve.
So, you need to add a route to your server that will response to a request for response.js. First change your <script> tag to this:
<script src="/response.js"></script>
You want the request to be "path absolute" so it does not depend upon the path of the containing page. Then, you need to add a route handler for response.js to your server.
This can be done as a single route:
app.get('/response.js', (req, res) => {
res.sendFile("response.js", {root: __dirname});
});
Or, you can use express.static() to serve a whole directory of publicly available files with one line of code (if you also move all publicly available static files to their own directory away from your server files).

Express routing does not work with simple test case

I think I am missing some concept with basic routing for Express. See here
I created some simple test code as follows in my server index.js file.
app.get('/foo', function (req, res) {
console.log('foo path found');
res.send('foo achieved')
})
In my browser(chrome) URL I type
localhost:3000/foo
to trigger the route but I get no response on the server or client.
I verified localhost:3000 is up and running.
Port is set in a different file as follows:
app.set('port', (process.env.PORT || 3000));
But also I get confirmation in the terminal as follows:
const server = app.listen(app.get('port'), () => {
console.log('DEBUG: express: server up');
});
I am on a campus network that blocks some traffic, but b.c. this is localhost I don't think it should matter.
I don't think you're supplying enough information to correctly debug your issue.
I'd initially ensure that Express is listening on port 3000, double-check this line:
app.listen(3000);
Ideally, this line should be at the bottom of the script.
Response to edit: Yes, this should not matter. localhost is an alias for the system itself. It's a loopback, similar to that of 127.0.0.1.
It seems like you have created two express app, as you have mentioned that you are using two different files, the localhost which you are able to run is the one which has app.listen() code, but this doesn't have the app.get()
I suggest you use a single file for now and try doing it.
Try out the following code, and check now with localhost:3000/foo.
const express = require('express')
const app = express()
const port = 3000
app.get('/foo', function (req, res) {
console.log('foo path found');
res.send('foo achieved')
})
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

How can I handle routing with express when I use a static site?

When the user goes to mydomain.com/game, I want the user to see what is displayed in my public folder. This works completely fine when I do this:
app.use('/game', express.static('public'))
The problem is that I want to extract some information from the URL, but as I do not know how to continue the routing when using a static site, I can't extract any information. For example, if the user inputs mydomain.com/game/123, I want to retrieve 123, but still route the person to my public folder, like mydomain.com/game does.
Any ideas on how to handle this problems?
This has worked for me in a similar situation
app.use('/game/:id', (req, res) => {
// do something with id
res.redirect(302, '/game');
}
Try to use two middlewares: first is your static middleware, the secont is the fallback, with id (123)
app.use('/game', express.static('public'));
app.use('/game/:id', function(req, res) { // when static not found, it passed to this middleware, this process it
console.log('your id', req.params.id);
res.send('ok');
});
If you are using react static files and you want to serve all react routes using express then you have to do thing like below-
1.First of all you have to run command in your react folder
npm run build
this will create your build folder in react app having one index.html file which you have to serve through express.
Now come to your server.js file and write there
const express = require('express');
var path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', (req,res) => {
res.sendFile(path.join(__dirname+'/client/build/index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server up and running on port ${port} !`));

Set Home Page in Express

I have some server side code in node js, which creates a express js object and runs the server. The app loads the index.html page which is inside the public folder. I have never written the code to serve the home page (mention below), still it works.
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'public/index.html'));
});
I have not written this code so how does the index.html gets rendered. My understanding says express JS looks for the first instance of index.html page in all the static folders declared in the code and renders it, in my case the static folder is "publimc" and it has index.html at the root level.
server code follows below, which I have written.
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('contactlist', ['contactlist']);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/publimc'));
app.use(bodyParser.json());
app.get('/contactlist', function (req, res) {
console.log('I received a GET request');
db.contactlist.find(function (err, docs) {
console.log(docs);
res.json(docs);
});
});
app.listen(8000);
console.log("Server running on port 8000");
The home page is rendered as part of the express.static middleware default options.
To disable this logic, set express.static(..., { index: false }).
If you want to change the file served as a home page, set express.static(..., { index: 'yourfile.html' }).
What this option does, in fact, is attempt to serve an index page with given file name for each directory in your public folder, so if you have public/foo/index.html then it will get served when requesting /foo/ path.

express.js to GET json file in terminal

How do I GET a JSON file with express.js? I want to be able to access it in my Mac terminal. I'm working on a college assignment that asks me to write an HTTP server that will act as a simple data store. It must respond to GET, PUT, POST, and DELETE requests. I must use express.js instead of fs for this app.
So far, in my root directory I have a server.js file and I have a subdirectory called lib that holds another subdirectory called notes. Notes is where the JSON files will live.
In my root directory, I have a server.js file. This is all I have so far:
'use strict'
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var notes = './lib/notes';
app.use(bodyParser.json());
app.get('/', function(req, res) {
//
//this is the part I need help with
//
}
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('Server started on port ' + port;
});
Once I have this GET request working, from my Mac terminal I should be able to send a GET request and receive all JSON files inside the notes directory.
...from my Mac terminal I should be able to send a GET request and
receive all JSON files inside the notes directory.
Provided you do not want to use fs module(well you dont need one either),
you can simply set a route for GET requests and send the json file in response with app.sendFile()
app.get('/',function(req,res){
res.sendFile(path.normalize(__dirname + '/foo.json'))
//assuming your app.js and json file are at same level.
//You may change this to 'lib/notes/foo.json' to fit you case
})
path is a module that you would need to require().
__dirname is the directory that the currently executing script is in.
and finally foo.json is the file containing your json
{
"name":"nalin",
"origin":"stackoverflow"
}
Here's the complete code for app.js
var express = require('express');
var path = require('path');
var app = express();
app.get('/',function(req,res){
res.sendFile(path.normalize(__dirname + '/foo.json'))
})
app.listen(3000);
Which will help you run the node server with node app.js.
Finally you can access the json with by
visiting http://localhost:3000/ on your browser
by running curl command on your mac terminal curl localhost:3000
Hope this helps.
You can serve your .json files as static:
app.use('/notes', express.static( notes ));
http://expressjs.com/starter/static-files.html
Or you can do it manually width path pattern:
app.get('/notes/:file', function(req, res) {
fs.readFile(notes + "/" + req.params.file, function(err, data) {
if(err) {
res.status(404).send('Not found');
} else {
res.contentType(req.params.file);
res.send(data);
}
res.end();
});
});

Categories

Resources