Node.js exports module not working - javascript

I am very beginner to node.js, I found a tutorial to learn. while I learn I used this code to run my server it works fine:
code :
var http = require ("http");
http.createServer (function (request, response) {
response.writeHead(200, {"Content-Type" : "text/plain"});
response.write("Hellow world! I written my first server side code!"); //browser responding
response.end();
} ).listen(8888);
But while I tried to export the server like this,
var http = require("http");
function start() {
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start; // the export module not work?
and i am getting an error in browser like this:
Failed to load resource: Could not connect to the server.
I am not able to start my server, and export the module any one suggest me the fix for this please?

Related

Node.js Server calling HTML calling Javascript Module: Disallowed MIME Type and/or "require" not defined

I'm using the Spotify API to make an app for a school project, but I'm having trouble on the front-end of the project. The idea is a Node.JS server is running an HTML file, which will call on a java script module which is attempting to import the Spotify API.
simpapp.js : Run in node.js command prompt with node simpapp.js
var path = require("path");
var express = require('express'); // Express web server framework
var request = require('request'); // "Request" library
var fs = require('fs');
var cors = require('cors');
var cookieParser = require('cookie-parser');
var app = express();
app.use(express.static(__dirname + '/public'))
.use(cors())
.use(cookieParser());
app.get('/', function (req, res) {
fs.readFile(path.join(__dirname, '/public', 'simpbutton.html'), 'utf-8', (err, data) => {
if (err) {
res.writeHeader(404, {
'Content-Type': 'text/plain'
})
res.write('404 Not Found');
res.end();
return;
}
if (req.url.endsWith('.html')) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
}
if (req.url.endsWith('.js')) {
res.writeHead(200, {
'Content-Type': 'application/javascript'
});
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
res.end();
});
});
console.log('Listening on 8888');
app.listen(8888);
simpbutton.html : called on by simpapp.js
<!DOCTYPE html>
<head>
<tile>Testing MIME Type Imports</tile>
<script type="module" src="/js/throwaway.js"></script>
</head>
<body>
<button onclick="basicAlert()">Click Me!</button>
</body>
throwaway.js : called on by simpbutton.html
//Produces Error "Loading module from “http://localhost:8888/js/spotify-web-api-js”
//was blocked because of a disallowed MIME type (“text/html”)."
import Spotify from "./spotify-web-api-js";
//Produces Error "ReferenceError: require is not defined"
//var Spotify = require("spotify-web-api-js");
// ^ I only will have one active at a time while the other is commented
function basicAlert() {
alert("this is a test to see if basicAlert runs properly");
}
console.log("Should print to console with no error on imports");
And spotify-web-api-js can be found here: https://github.com/JMPerez/spotify-web-api-js
Both my errors are seen in console when running the server (details seen in throwaway.js).
I have already seen Node server: Loading module was blocked because of a disallowed MIME type (“text/html”) which is extremely similar, but its answer did not solve my problem.
Any assistance to get either of these import methods work would be appreciated. Thanks
EDIT: In case it's wondered, the file structure is not the issue; that has been tested with a "text/javascript" script in HTML without the imports and it works perfectly then.
new throwaway.js:
import * as Spotify from "./spotify-web-api.js";
window.basicAlert = function basicAlert() {
alert("this is a test to see if basicAlert runs properly");
}
console.log("Should print to console with no error on imports");
importing the file as * as Spotify enables the import and avoiding the MIME type error while window.basicAlert will submit my basicAlert function to the file that imports it (otherwise basicAlert is not defined).
I'm surprised no one else answered on the import * as Spotify from cause it seems like such a simple error.

Syntax error with NodeJS and HTTP

var http = require("http");
http.createServer(function(request,response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.writeHead(" This is just a start.. Remember what u thought of it.");
reponse.end();
}).listen(8888);
This is my JS code in a file named server.js which I wanted to execute through Node.js, but it's giving an error:
SyntaxError: Unexpected identifier
The path of the file, server.js is in D Drive, same as where I installed Node.js. What should I do ?
Use this code:
var http = require("http");
http.createServer(function(request,response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(" This is just a start.. Remember what u thought of it.");
response.end();
}).listen(8888);
Save it in a file named "server.js" and run it with:
node server.js
I don't know if it's a typo in your question but you use reponse instead of response:
var http = require("http");
http.createServer(function(request,response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.writeHead(" This is just a start.. Remember what u thought of it.");
reponse.end(); // <------
}).listen(8888);

how print modules on web

var http = require('http');
function start() {
function onRequest(req, res) {
console.log("Request received.");
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
var procfs = require('procfs-stats');
var ps = procfs(process.pid);
function sysUsage() {
ps.io(function(err, io) {
console.log('My process has done this much io', io);
});
}
exports.sysUsage = sysUsage;
here is my code, I am new in Node.js
how can i print "procfs-stats" and "libCpuUsage" on web?, not in console.
thanks
You need a template engine, there are many (http://garann.github.io/template-chooser/), common ones are:
Jade
EJS
But it's up to you to choose your preferred for your Node application.
Probably the best option for you is to install and use ExpressJS framework in your Node.js app, it gives you a powerful suite of features to be used in your app.
And of course, it gives you a simple way to add a template engine too.
Please refer to this for your specific needs: Using template engines with Express

Running Node.js Server using User Level Root

Basic question but not sure where to turn to start figuring this out.
I've setup a very simple node server on port 3000 that just responds with an index.html file. When I call http://localhost:3000 in the browser, I get the proper page served up with dependencies. I don't want to authenticate every time though so I'd like to run it from the user-level.
I tried typing http://localhost~myusername:3000 in the browser but I keep getting:
The requested URL /~myusername:3000 was not found on this server.
(I have setup user-level root to be accessed through ~/Sites and have gotten access to files through here, even php, it's just when I start using a node server this problem occurs.)
How can I get node.js to respond to user-level requests? And it serve up the proper index.html from the relative path of the user-level root instead of /library/WebServer/Documents?
Update
Code of server.js:
var http = require('http');
var fs = require('fs');
function send404(response) {
response.writeHead(404, { 'Content-Type': 'text/plain' });
response.write('Error 404: Resource not found.');
response.end();
}
var server = http.createServer(function (req, res) {
if (req.method == 'GET' && req.url == '/') {
res.writeHead(200, { 'content-type': 'text/html' });
fs.createReadStream('./index.html').pipe(res);
}
else {
send404(res);
}
}).listen(3000);
console.log('server running on port 3000');

Node.js webserver CHUNKED encoding issue

I'm trying to build a node.js webserver that listens on port 9000 and reads a js file when requested then sends the output on the response. This is what I have so far:
var http = require('http'),
fs = require('fs'),
path = require('path');
http.createServer(function(request, response){
response.writeHead(200, {'Content-Type': 'text/javascript'});
switch (request.url){
case '/main.js' :
fs.createReadStream(path.normalize('C:\\dev\\projects\\main.js')).pipe(response);
response.end()
break;
case '/page.js' :
fs.createReadStream(path.normalize('C:\\dev\\projects\\src\\page.js')).pipe(response);
response.end()
break;
case '/page2.js' :
fs.createReadStream(path.normalize('C:\\dev\\projects\\src\\page2.js')).pipe(response);
response.end()
break;
default :
response.writeHead(404);
response.write('Not Supported');
response.end();
break;
}
}).listen(9000);
console.log('listening on port 9000........')
I call the main.js file from the HTML page like so:
<script type="text/javascript" src="http://localhost:9000/main.js"></script>
When running the page, the first case in the code should run but all I get is this error in the browser console.
GET http://localhost:9000/main.js net::ERR_INVALID_CHUNKED_ENCODING
I tried playing around with the headers in the response with no success. Any ideas?

Categories