Need help getting simple node.js express to run - node.js

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

Related

How to combine vue-cli development mode with server-side api?

I'm new to vue and kind of confuse here.
I'm using vue-cli to build a vue app, I understand I can run a development server with npm run serve which is referenced as a script in my package.json for vue-cli-service serve
But my app need some data coming from a local node.js server. I cannot request this server from development mode because it's running on a different server.
To make my app work I'm obligated to build for production with
npm run build
Then to ask my node server to render by default the produced index.html file.
How could I combine development mode and my node server?
What would be the best way to make this work?
Thanks a lot
I stumbled across this, and found the answer buried at the bottom of the comments list, so I thought I'd highlight it.
This answer is taken from #Frank Provost comment, which really should be the accepted answer. As mentioned in his link https://cli.vuejs.org/config/#devserver-proxy all you need to do is create/edit vue.config.js file in your (client) project root to include this:
module.exports = {
devServer: {
proxy: 'http://localhost:3000' // enter dev server url here
}
}
Then start your dev server as usual from your server project:
[server-root]$ npm run dev
And run your client project from vue-cli project
[client-root]$ npm run serve
Then when you visit the client url (usually localhost:8080) all api requests will be forwarded to your dev server. All hot module replacement still works on both client and server.

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

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

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

Running node.js server with mongodb error

I'm still new to node.js and mongodb. Now I'm trying to solve this problem.
I have instructions to run my server without any problems, I follow them and yes my server works. But when I switched the server off then run it again I face this bug:
[vagrant#localhost ~]$ node /opt/inapsrv/app/app.js
app-api listening at http://0.0.0.0:7000
/opt/inapsrv/node_modules/fileupload/lib/modules/file.js:23
throw error
^
Error: ENOENT, mkdir 'data/imagex/'
And here is the line of the directory above taken from app.js file:
var imagePath = 'data/imagex/';
I tried to:
make vagrant and mongo users as super users and they have the root permissions.
to run "sudo node /opt/inapsrv/app/app.js"
run "forever /opt/inapsrv/app/app.js"
and it didn't work.
I don't know why it successfully ran the first time, and then it didn't!
Any help?
I suspect you're using node module fileupload for the upload job. The source code fragment in fileupload that throws your error can be found here.
The problem with the code used in fileupload module is that it does not create recursive directories since fs.mkdir is used. To fix your issue try to create the upload directory or at least data upfront. You could do this by a npm script, in app.js using the mkdirp or simply by a shell script.
The problem described is not related to mongodb or mongoose.

Resources