node js syntaxError: Unexpected Identifier - node.js

There are a lot of questions regarding this issue, but none of them were helpful, as they fix a concrete syntax error. I'm really new in Javascript programming, starting it a few weeks ago.
I would like to run my scripts on Node.js, but for some reason it is not working. It gives me the next error: SyntaxError: Unexpected identifier
I'm talking about very simple scripts, like this:
var orders =[
{amount: 250 },
{amount: 400 },
{amount: 100 },
{amount: 325 },
];
var totalAmount=0
for(var i=0; i< orders.length; i++){
totalAmount+=orders[i].amount;
}
console.log(totalAmount);
What basically is working on my browser smoothly.
I'm really sorry to bother you with such small silly things, but I would appreciate any help. It's easier to work with my scripts on node js.

How are you running your scripts in nodejs? If you are just starting with js, try it in browser. Or if you really want it with nodejs.
Download the Windows executable here: http://nodejs.org/#download
Copy the file to C:\
Create C:\hello.js
Paste in the following content:
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 127.0.0.1:1337');
Save the file
Start -> Run... -> cmd
c: C:>node hello.js

It seems I've got the problem, I tried to run the things through the language shell window instead of node.js command prompt.It's silly I know, but it wasn't specified where to run the node commands. By the way I found out more, then I was expecting. I don't regret to register here, you have a lot of material here. Thank you guys.
I hope one day I can help out someone.

Related

Error getting when executing nodejs through command prompt

I have the below code in Nodejs and tried to execute the same through command line as well as in browser, but getting "unexpected identifier" error.
var http = require('http');
http.createServer(function(request, response) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end('<b>Running in server...</b>');
}).listen('3000', '127.0.0.1');
File name created is module3.js
I am very new to nodejs. So can anyone please help me to resolve this. Thanks!!
If you like to run file, do it as usual for shell comman line (interpreter file):
D:\nodejs> node module3.js
If you like to work in nodejs command line, you need to load module by require and it will be loaded and evaluated:
D:\nodejs> node
> require('./module3')
If your module exports some function you may to call it:
D:\nodejs> node
> require('./module3')()
Check about exports here

Node.js not working on Windows XP machine

I am just getting started with node.js and I have followed multiple tutorials to get it working on my Windows XP machine.
Downloaded the msi and installed with no issues, opened a command prompt and typed node -v and nothing displays. I created a folder and made a JS file with console.log('hello'); in it, changed to that directory and typed node hello.js and nothing shows.
I then added this code to the hello.js file:
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 ran the file from the command line again, it paused briefly and then again displayed nothing.
Been through 10 different tutorials on 10 different sites and can't find a thing to answer this question, even all the information here was no help at this point.
I have also checked the path and it is fine and rebooted the machine just in case.
Seriously stuck!
You need to set your path to node (Environment Variable). Check the following address:
http://www.hacksparrow.com/install-node-js-and-npm-on-windows.html
This is necessary for running node from any folder in the system.
Or you can add node as an enviroment variable in Windows XP's settings:
https://support.microsoft.com/en-us/kb/310519

Cannot run node.js example. module.js:340 throw err cannot find module

When I type in node example.js to my command prompt it gives me an error message.
This is the code I'm using.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, 'localhost');
console.log('Server running at http://localhost:1337/');
I got that directly from the node.js website and it worked last night. It won't work today. Some help would be appreciated please.
Node.js looks for the file you pass it in the current directory.
If the file only exists in a different directory, it will not be able to find it.
You need to either save the file to the correct directory, or use cd to switch to the directory containing the file.

display html page with node.js

This is my first time with node.js. I get it to display the index.html, but it doesn't display the images on the site or anything else, it ONLY shows the basic html stuff. Here's how I set it up.
There's no apache, php or anything else on the server, just ubuntu, proftp and node(and curl and the other dependencies). I made the main directory for the node files /var/nodeFiles and the directory for the html/site files is /var/nodeFiles/www
so for my node server file I did it like this:
var http = require('http'),
fs = require('fs');
fs.readFile('/var/nodeFiles/www/index.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(80);
});
this works, but it ONLY shows the index.html file and NOTHING attached to it, so no images, no effects or anything that the html file should display. The files and directories are all correct, I've double checked and the permissions of the folders are correct. So what else do I have to do to get node to display the rest of the site?
I hope I've explained my self correctly, I was told this is the place to ask development questions.
Thank you for taking the time to read this.
but it ONLY shows the index.html file and NOTHING attached to it, so no images,
no effects or anything that the html file should display.
That's because in your program that's the only thing that you return to the browser regardless of what the request looks like.
You can take a look at a more complete example that will return the correct files for the most common web pages (HTML, JPG, CSS, JS) in here https://gist.github.com/hectorcorrea/2573391
Also, take a look at this blog post that I wrote on how to get started with node. I think it might clarify a few things for you: http://hectorcorrea.com/blog/introduction-to-node-js
Check this basic code to setup html server. its work for me.
var http = require('http'),
fs = require('fs');
fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8000);
});
This did the trick for me:
var express = require('express'),
app = express();
app.use('/', express.static(__dirname + '/'));
app.listen(8080);
If your goal is to simply display some static files you can use the Connect package. I have had some success (I'm still pretty new to NodeJS myself), using it and the twitter bootstrap API in combination.
at the command line
:\> cd <path you wish your server to reside>
:\> npm install connect
Then in a file (I named) Server.js
var connect = require('connect'),
http = require('http');
connect()
.use(connect.static('<pathyouwishtoserve>'))
.use(connect.directory('<pathyouwishtoserve>'))
.listen(8080);
Finally
:\>node Server.js
Caveats:
If you don't want to display the directory contents, exclude the .use(connect.directory line.
So I created a folder called "server" placed index.html in the folder and the bootstrap API in the same folder. Then when you access the computers IP:8080 it's automagically going to use the index.html file.
If you want to use port 80 (so just going to http://, and you don't have to type in :8080 or some other port). you'll need to start node with sudo, I'm not sure of the security implications but if you're just using it for an internal network, I don't personally think it's a big deal. Exposing to the outside world is another story.
Update 1/28/2014:
I haven't had to do the following on my latest versions of things, so try it out like above first, if it doesn't work (and you read the errors complaining it can't find nodejs), go ahead and possibly try the below.
End Update
Additionally when running in ubuntu I ran into a problem using nodejs as the name (with NPM), if you're having this problem, I recommend using an alias or something to "rename" nodejs to node.
Commands I used (for better or worse):
Create a new file called node
:\>gedit /usr/local/bin/node
#!/bin/bash
exec /nodejs "$#"
sudo chmod -x /usr/local/bin/node
That ought to make
node Server.js
work just fine
You can simply use
res.senFile('PATH_TO_FILE');

Why does Cloud9 IDE return the error "Script does not exist" when trying to run simple Node.js script?

I am attempting to create a simple Hello World Node.js script using Cloud9 IDE. My code is below and is the atypical 6 lines:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(process.env.PORT);
I don't see any errors and the IDE is certainly not alerting me to any. I've ensured that the file is saved (even going so far as to commit it to my repo). Unfortunately, whenever I try to run the above code I receive the following error:
Error on server
Received following error from server:
"Script does not exist: server.js"
To illustrate the run configuration I've included the below screenshot:
I am pretty sure I am missing something obvious, but whatever it is its alluding me. What do I have misconfigured that could cause my server.js file to not run?
Your configuration is correct, there is however a temporarily problem that causes some of the VM's to not run a file. I've seen it before and it usually goes away after some time. Quick fixes now:
Either wait
Create a new project with the same file, chances are that it'll run
Your filepath doesn't look right. Shouldn't it be server.js and not /server.js? Try creating a new run configuration and set the file path to server.js.

Resources