Determine & change DocumentRoot/port of node.js & run a function w/parameters - node.js

How do I determine and change both the "DocumentRoot" equivalent (of Apache) and port number on Node.js? I need to test a script file by calling the function and passing some parameters (yes, I know the file can execute it automatically).
There is no "getting started" or mention of this in the documentation.

Apache HTTPD is a generic web server. Node.js is a development framework that includes a standard library for creating HTTP servers. Thus, there isn't a standard configuration for a Node.js based application like there is for Apache HTTPD.
The basic example of writing a web server with Node.js is found at https://nodejs.org/api/synopsis.html#synopsis_example
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Which is to say, you define where files are loaded from and what port they are served over.
This is where frameworks like Fastify, Hapi, and Express come in. The make it easier to write generic web servers.

I first installed Node.js and it just has a command prompt in Windows. Still not sure the port number.
Node seems to execute scripts from it's directory (e.g. C:\Node.js\). As James mentioned in another answer Node.js doesn't do much on it's own. I followed a tutorial on getting Express to work on Windows. The tutorial failed to mention where scripts are run from so ignore the directions past running the following on the normal command prompt (not Node's console):
Run npm install
npm install express -g
npm install url -g
npm install fresh -g
npm install cookie -g
npm install methods -g
npm install crc -g
npm install send -g
npm install connect -g
npm install commander -g
npm i -D run-func
Okay, the last line of code allows us to run a function and pass parameters which I found via Pawel's answer here.
So now I can execute the following:
node run-func "C:\Users\John\HTTP\index.js" function_name param1 param2

Related

BASH: express command not recognized

I've read other forums on installing express, I have run
npm install express -g on command prompt as admin.
I did this command a few times and restarted my computer multiple times but Express is still not recognized.
Any help is appreciated.
Express isn't a web server; it is a framework for building web servers.
The express package doesn't provide anything directly executable.
The express documentation has a getting started guide.
If you aren't trying to do server-side programming using Node.js and just want an HTTP server, then the http-server package may be more your speed.
Assuming you’ve already installed Node.js, create a directory to hold your application and make that your working directory.
then follow the below command
npm init
follow step press enter and after
npm install express
make index.js file paste below hello work program.
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Now you can run file using below command
node index.js
Open your broswer and enter URL : http://localhost:3000/
You can display Hello World!
You have successfully installed node js and express js program.

Howto run google assistand bitcoinInfo example webhook index.js

I am trying to run the google assistant example webhook nodejs application(index.js) on my own server, but don't know what is the webhosting setup for this..
https://codelabs.developers.google.com/codelabs/your-first-action-on-google-with-webhook/#2
What is the environment to run this app on my server? Since it's not running as a listening server, I can't use nginx, node_cgi is not mature with apache, how am I supposed to run this sample?
Excellent point, and you should be sure to file a bug request on the page to indicate it is unclear.
The code, as presented, is meant to run using Google Cloud Functions.
This doesn't mean you can't run it on your own server - just that you need to know how to run a Node.js server outside of your Apache or Nginx environment. I've seen a number of configurations, but typically you'll have the Node.js server application running and listening to a local port and have a proxy between your externally facing web server at a particular path and this port.
But even that isn't sufficient in this case - the code itself doesn't listen on a port - it expects to be handed a request and response object in the form that Express.js with a JSON middleware can handle. To do that, you'll need to have installed the Express.js library and then start listening with code such as:
const express = require('express');
const app = express();
app.use( express.json() );
app.get('/', (req, res) => exports.bitcoinInfo( req, res ));
app.listen(3000, () => console.log('App listening on port 3000!'));
Thanks for the help to #Prisoner and #Ido Green link works even better! The minimum to run the sample I did the following:
Create a new nodejs project with mainfile main.js, install express and actions-on-google
mkdir googleActionServer
cd googleActionServer
npm init
npm install --save actions-on-google
npm install --save express`
Copy the index.js from google and put this into main.js
const express = require('express');
const bitcoinInfo = require("./index");
const app = express();
app.use( express.json() );
app.post('/', (req, res) => bitcoinInfo.bitcoinInfo( req, res ));
app.listen(3000, () => console.log('App listening on port 3000!'));
Start the application by running:
node ./main.js
To test with DialogFlow, download and install ngrok to /usr/local/bin for ex and then run:
ngrok http 3000
Ngrok will give you an url that is accesible from outside and forward the requests to the nodejs app. It will also create a https for you, so copy paste the https address into DialogFlow webhook address and you are set to go

Need help getting simple node.js express to run

I'm trying a simple sample of node express that I copied from online. The script is below which I think is pretty standard.
var http = require('http');
http.createServer(function(request, response)){
response.writeHead(200);
response.write("hello");
response.end();
}).listen(8080);
console.log('listening on port 8080...');
I used the bash on ubuntu on windows command as follows:
npm init
node SampleServer.js (the name of my file)
When I do this, I expect some response from the command line. But when I enter the "node SamplerServer.js" command, nothing happens. When I direct the browser to port 8080, I get an error message as well.
I'm using nodeclipse and the installing that on my machine was pretty complicated. Prior to any of the steps above, I created an express project in eclipse ide. It seems to perform a lot of pre steps but in the end, I think I'm getting some of the error messages below. I'm mentioning this because I'm thinking perhaps I installed one of the modules wrong.
enter image description here
Start with simple stuff...
Use express-generator to create simple app by the following command
1-> npm install -g express-generator with root or Admin access
2-> Run express demoapp.
3-> Navigate to demoapp
4-> Do npm install
5-> Run from command with npm start: it run by default on http://localhost:3000
Hit that URL from Browser

How to install node.js and create project in Eclipse

The steps I've tried:
1.(OK) install node from official website: https://nodejs.org/en/download/
Result: I'm able to open cmd(in any location, type node then use commands like "console.log" and it prints my messages)
2.(Failure) install express using npm install -g express from cmd gives me an error(picture attached
3.(OK) I've succeed installing express using the following command npm install express (without -g)
4.(OK) Writing a simple Hello World program works. Javascript file:
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
5.(Failure) However, I wanna run a bigger project, where besides one js file, I also have an index.html file. If I move both files to node installation directory, everything works. But I wanna be able to keep my projects somewhere else. If I try to run with node C:\Users\marius\Downloads\chat-example-master\indes.js I get the error: Cannot find module express. Thus it seems that when I installed express without "-g" I got it working only in node directory.(let me know if you have any doubt).
6.(Failure) When creating a Node.js project from Eclipse, I choose empty project, no template, then add a single and simple js file(the one with Hello World), right click on project name -> run as -> run Configuration -> Node Application -> New -> add my .js file -> Run. I get the following error:
Exception occurred executing command line.(steps from http://techprd.com/how-to-setup-node-js-project-in-eclipse/)
Cannot run program "node" (in directory "C:\Users\marius\workspace\FirstNodeProject"): CreateProcess error=2, The system cannot find the file specified
To recap: What I want is to be able to run node projects located anywhere with "node" in cmd and to create node.js and express project and run them from Eclipse.
Please let me know if you need more information.
Just to let others know if they come across this issue. I can run express apps from anywhere but in the root folder of every app I have to npm install express.
In Eclipse all you need to do is: Window->Preferences->Nodeclipse->uncheck "find .Node on PATH" and insert into Node.js path input your node.exe location (in my case: C:\Program Files\nodejs\node.exe)

Node,js doesn´t find any modules

I am trying to do one of the node-horseman examples, but I am finding with a problem. The example I am trying to follow is this:
var Horseman = require('node-horseman');
var horseman = new Horseman();
var numLinks = horseman
.open('http://www.google.com')
.type('input[name="q"]', 'github')
.click("button:contains('Google Search')")
.waitForNextPage()
.count("li.g");
console.log("Number of links: " + numLinks);
horseman.close();
And the errors it throws when I make phantomjs example.js are these:
Error: Cannot find module 'http'
phantomjs://bootstrap.js:299 in require
phantomjs://bootstrap.js:263 in require
:3
Error: Cannot find module 'tty'
phantomjs://bootstrap.js:299 in require
phantomjs://bootstrap.js:263 in require
:6
TypeError: Object is not a constructor (evaluating 'require('debug')('horseman')')
:5
TypeError: Object is not a constructor (evaluating 'new Horseman()')
phant.js:2 in global code
I try to install http locally using npm install http, but after this, there is only a package.json on example/node_modules/http, and if I use npm install in this location, it throws three warnings:
it is too the name of a core module
no description
no repository field
About tty, making a local installation it throws a 404 error.
I try this solution (include npm folder on the path) Nodejs Cannot find module but it didn´t work.
Any suggestion??
Thanks.
EDIT
NOT SOLUTION
I reinstall node (now my version is node 0.12.3, npm 2.9.1, and phantomjs 1.9.8), when I try this simple example from the nodejs web:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
And if I run "node example.js" it works, but if I do "phantomjs example.js" the problem persists "Cannot find module http".
I tried install phantomjs via npm ("npm install -g phantomjs") and via downloading the zip on their web, unzipping and adding to the PATH the route to unzipped folder.
One more data (maybe could be a help) my SO is Windows 8.1.
RE-EDIT
I am watching that on the folder where I have installed node, the only folder on node_modules is npm, is it right?? And on C:\Users\Eloy\AppData\Roaming I have two npm folders, one of them is npm-cache and the other one simply npm. The node_modules of this last one doesn´t contain the http module, the npm-cache has a lot of modules and http incluiding... is it important??
Thanks.
+1 your observation in first EDIT i.e scripts run like $ phantomjs can't access global modules via require(), it can access local modules though. Not sure if this is a documented shortcoming of phantomjs

Resources