Convert Nodejs server into node module - javascript

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;')
}
}

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

What is this express variable is doing?

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.

Can't run puppeteer in react app, Module not found: Can't resolve 'ws' when compiling

I was wondering if it was possible to run puppeteer in my react app. Whenever I try to run puppeteer in my react app I get "Module not found: Can't resolve 'ws'". I've tried installing ws but will still get the same error.
Simple answer : You can't run puppeteer in react app.
React is a client side framework. which means it runs in browser.
While puppeteer is a NodeJS lib, it needs Node.js and runs on server side.
Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol. Puppeteer runs headless by default, but can be configured to run full (non-headless) Chrome or Chromium.
Expanding on the above answer. You cannot directly run Puppeteer on a react app. React app is a frontend framework and you would need Puppeteer to run on a node js, server. It's a simple "fix" and I wanted to explain it a little more than the answer above does.
The steps to get them to work together would be.
Setup an express server. You can create an express server like so:
Separate directory reactServer. Npm init directory and npm i express.
In your express server you allocate a path
const express = require('express')
const app = express()
const port = 5000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.get('/my-react-path', (req, res) => {
// run any scripts you need here
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
Then your react app will interact with your server like so:
localhost:5000/my-react-path
In the my-react-path you can create a function that fires up puppeteer and does all the things you want on the server side and it can return whatever results to React. The above example is just to get you started it doesn't have anything related to puppeteer.

How do I add Swagger to an existing Node app?

The documentation for Swagger (https://github.com/swagger-api/swagger-node) only shows how to create a new app. How do I integrate Swagger into an existing API app?
I followed this guide: https://blog.cloudboost.io/adding-swagger-to-existing-node-js-project-92a6624b855b
npm i swagger-ui-express -S
I used the Swagger editor to create a swagger.yml file. http://editor.swagger.io/
I added this to my server:
var swaggerUi = require('swagger-ui-express')
var fs = require('fs')
var jsyaml = require('js-yaml');
var spec = fs.readFileSync('swagger.yml', 'utf8');
var swaggerDocument = jsyaml.safeLoad(spec);
...
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
I was then able to access Swagger docs via http://localhost/api-docs.
It's unfortunately not the same level of integration that Swagger has with Spring Boot in Java, where you can add an annotation and Swagger will automatically generate the documentation for you. It seems Swagger for Node requires you to maintain the swagger.yml documentation manually. I have my routes defined like app.use('/users', userRouter) and inside the users.js file I have functions defined like router.post('/status', (req, res) => { ... }. That doesn't seem compatible with Swagger for Node, which has a concept of operationId which somehow points to a function name.

Combine Angular 2 application server and REST server modules

I am creating a new Angular 4 application. I have followed it's official tutorial https://angular.io/tutorial/
The application server is started using ng serve command.
I have created a separate node js (+express) server that provides the REST services to the main app on a different port.
Is there any way to serve the main angular application from the same nodejs/express server so that i don't have to use two servers for the application?
I have used typescript which needs to be somehow compiled into plain javascript before statically being served via nodejs, if i understand it right?
Absolutely, just use ng build and serve the dist folder of the built application, or even the src. Example:
const staticFor = rel => express.static(path.resolve(__dirname, rel));
const app = express();
if (!config.production) {
app.use('/node_modules', staticFor('../node_modules'));
// In development we do not copy the files over, so map used path
}
app.use('/', staticFor('../dist/app'));
const appPath = path.resolve(
__dirname,
config.production ? '../dist/app/index.html' : '../src/app/index.html'
);
app.get('/yourAppPath/*', (req, res) => {
const markup = fs.readFileSync(appPath, 'utf8');
res.send(markup);
});
Dont forget to require the right libraries.

Categories