What is this express variable is doing? - javascript

I recently started learning JS and I am a basic programming background previously but always stuck on OOPs concepts.
So here we are importing I think the express module by writing the required (express). But I don't understand why we are storing this in a variable.
Likewise then storing express() in app variable then using app variable to do some stuff.
I mean how's this is working? What is What in this code block? Please explain in detail.
Thanks in advance.
const express = require('express')
const { createReadStream } = require('fs')
const app = express()
app.get('/' , (req,res) => {
createReadStream('index.html').pipe(res)
})

Line 1: You import the express node module that you installed with npm i express and store it in a constant (const).
Line 2: You import the function or variable createReadStream from the file system module of node.js (fs module) and make it available for use in this file.
Line 3 you assign the express() function from the express module above to a constant called app, so you now have everything express related available to you on the app constant.
Line 4-5: You use the get method from the express() function you have stored in the app constant, and create a route for the base url of your app / (e.g. domain.com/ or localhost:8000/). If you request something from the server you send a GET request. If you send some data use POST or PUT, for example, the express() function in app have these methods for you to use, too (app.post for example).
When Postman or a regular user with a browser hits this part of your domain (route) with a GET request, the arrow function on line 4 (req, res) => kicks in. It takes in the request (req) and the result (res) parameters so you can use those inside of the function if you wish. On the req parameter you have available whatever is in the body the user sends in from a form, for example. In your case your route streams back a html file to the user via http in order to display it in the user's browser.

Related

Using dotenv for API keys in multiple JS files

I am new to web programming but not programming in general. I use node.js to create a website and am using dotenv to hide API info form github and am having some trouble understanding something.
My .env file is in the root directory and contains:
GOOGLE_CALENDAR_API_KEY=key_value
I use an app.js file to set up and run my server and send the index.html file.
//jshint esversion:6
const https = require('https');
const bodyParser = require("body-parser");
const express = require("express");
require("dotenv").config();
const app = express();
app.use(express.static("public"));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
app.listen(5000, function(req, res) {
console.log("Listening on port 5000.");
});
Then I have another script file I use named "custom.js" to run the bulk of my webapp. Inside, I try to use process.env to get the API key.
window.onload = function()
{
const googleAPIkey = process.env.GOOGLE_CALEDAR_API_KEY;
.
.
.
but I get an error "Uncaught ReferenceError: process is not defined"
I have also tried moving the require("dotenv").config() line to the custom.js file and that fails. There is something I am doing wrong with trying to access information from one file into another, but I don't understand what.
Any help would be appreciated!
From what's i understood you trying to access the process variable of node.js app from the client browser and it is not possible. The process variable is only accessible in the scope of the node.js application and not in the browser where you run your client.
you have to add require("dotenv").config(); on second script file also
It looks like you are trying to access the Process variable on the client-side / frontend. You cannot access those variables from a client browser or machine

Is Express.js platform-independent?

I'm just starting out with Express.js. In the official getting started guide, they showed the following basic code:
var express = require('express')
var app = express()
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
res.send('hello world')
})
The first parameter to app.get() is a forward-slash indicating the root directory. But the slash is a backward-slash in windows systems. Does express deal with these differences automatically, or do we need to write extra code for it? When I was using the http module, I did have to consider and correct for these differences. Thanks for the help!
app.get('/', ...) declares a handler for when an HTTP GET request is made to the URL path /. E.g. http://localhost:8080/. It has nothing to do with file paths on the server’s file system. If you use any functions that do take a file path, you may have to account for the differences between Windows and *NIX, that depends on the function.

Is it a normal to make http request on node.js

I'm using SSR with react and i18next. I don't have a lot experience with Node.js, so the question is:
Is it a normal way to make an external http request in a start of a server script execution and pass all the left server script code into the then function of a returned Promise instance as a later continuation part of the script.
Server code which is bundled and then is started
server.js
import express from 'express';
import promiseRequest from 'request-promise';
import i18next from "i18next";
import middleware from "i18next-express-middleware";
import render from './render';
const app = express();
promiseRequest.get('https://api/localization')
.then(data => {
i18next.use(middleware.LanguageDetector);
i18next.init();
app.use(middleware.handle(i18next));
app.listen(3000, () =>
console.log('App is running')
);
return app;
});
The reason I go this way is because I need to init i18n based on a response from a server.
Why do you need to make an api request to figure out your localization needs? Wouldn't that be a part of the incoming request to your static server (gimme the website in english, french, etc)? I'm unclear about your use case. Are you trying to have several instances of your static server to serve different languages?
A common model I've seen is to have multiple static files pre-generated, per localization, and then serve them up based on the request, ex: have a route that returns the english version when the user makes a request to http://yourwebsite.com/en, the french one at http://yourwebsite.com/fr or http://yourwebsite.fr, etc.

Convert Nodejs server into node module

Is it possible to convert a nodejs API server into a node module, which can be used for other projects without making much code changes?
Details: There are several API's(get, post, put) in the node js server. So if I use this server as a node module inside another node server, I must be able to access the API's in the node modules directly from the client. Is this possible? If yes, how?
I am required to do a POC on this for a client requirement and so far did not find it possible. Can you please help? I am relatively new to node js development
main script
const express = require('express');
const app = express()
/*
use some middlewares
*/
require('my-module')(app)
const server = http.createServer(app).listen(process.env.PORT);
module.exports = app;
module
module.exports = (app) =>{
app.get('/',(req,res) =>{
res.send('hi im a diffrent module;')
}
}

Why do I need to pass an express server instance as a parameter to the http module in Node.JS?

I'm currently studying Node.JS, Express.JS and Socket.IO. The tutorials that I've seen so far use a complicated sequence of code in order to initialize each of those modules:
var express = require("express");
var app = express();
var server = require("http").createServer(app);
var io = require("socket.io")(server);
Why is the variable "app" passed as a parameter to the variable "server" and server passed as a parameter to "io"?
Thank you in advance.
express (which is not part of node.js) is implemented as a request listener with which you can initiate the http server implementation provided by node.js.
Check the docs:
https://nodejs.org/api/http.html#http_http_createserver_requestlistener

Categories