If you are familiar with NowJS, one you start an instance of Now on the server, you can access a file located on the server by <script src="http://localhost:8080/nowjs/now.js"></script>
Any ideas on how to implement this?
Thanks,
Mark
There are many static file handler modules already in node, take a look at:
https://github.com/joyent/node/wiki/modules#wiki-web-frameworks-static
Most popular are:
https://github.com/felixge/node-paperboy
and
https://github.com/cloudhead/node-static
Using node static is as simple as:
var static = require('node-static');
var file = new(static.Server)('./public');
require('http').createServer(function (request, response) {
request.addListener('end', function () {
file.serve(request, response);
});
}).listen(8080);
Related
I get the following error message when I try to run a local node server with a very simple application (see coding below).
Loading module from “http://localhost:8080/importing.js” was blocked because of a disallowed MIME type (“text/html”).
I am new to node and ES6 Modules so I dont really understand the details of the problem. According to this URL the mime-type 'application/javascript' has to be served explicitly for modules. But how do I achieve this in my example below?
index.html
<!DOCTYPE html>
<html>
<head>
<script src="./importing.js" type="module"></script>
<meta charset="utf-8">
</head>
<body>
</body>
</html>
server.js
var http = require('http');
var fs = require('fs');
const PORT=8080;
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(PORT);
});
importing.js
import {a} from './exporting.js';
console.log(a);
exporting.js
export const a = 'Constant a';
I start the server in CMD with
node server.js
Essentially you have a server that for any given request, serves the content of your index.html file - regardless of what that request might look like. A browser therefore receives the HTML and begins to interpret it making another request for the src of your script tag and since the server only serves your index.html file, the browser receives your HTML file a second time when it expected javascript.
Typically you'd create a server first then construct responses based on the request as input. A primitive example of serving your static files how you intended might look like the following:
const http = require('http')
const fs = require('fs')
const PORT = 8080
http
.createServer((request, response) => {
fs.readFile(`.${request.url}`, (err, data) => {
if (err) {
response.writeHeader(404, {
'Content-Type': 'text/plain'
})
response.write('404 Not Found')
response.end()
return
}
if (request.url.endsWith('.html')) {
response.writeHeader(200, {
'Content-Type': 'text/html'
})
}
if (request.url.endsWith('.js')) {
response.writeHeader(200, {
'Content-Type': 'application/javascript'
})
}
response.write(data)
response.end()
})
})
.listen(PORT)
Do note that this example is too trusting of the client and you would normally want to sanitise the request in some way. I kept to vanilla javascript but once you're comfortable with how it works, it's worth checking out Express as it will simplify the routing / mime-type boilerplate etc.
I know that you're importing just the command, but I'll let you know my solution for this and see if you're interested. This error, for me, came from the import statement in your module. I was trying to import the entire file, with all functions and imports it had, while essentially using the same server and HTML.
my importing.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");
I don't know the logic behind the import * as, but it worked to successfully import my file without throwing a MIME type error. As for the window.basicAlert =, Javascript apparently doesn't like to give any file that imports it access to its functions or variables unless it's manually attached to the window. You don't have this error now, but after the file imports successfully it will tell you that a isn't defined. While I have it attached to my function in importing.js, you'll need to put it in exporting.js like this:
const a = 'Constant a';
windows.a = a;
I didn't test that ^ but it makes sense to me. I hope this can help you out, or get closer, cause it solved my problem.
i'm running the server using node.js on localhost:8080 and i want to use api's in my HTML document. the html document is external, so how would i go about sending the api data to the web page. for example, i have a weather api in my javascript file:
var yw = require('weather-yahoo');
var ans = {};
function loadWeather() {
yw.getSimpleWeather('denver,co').then(function(res){
console.log(res);
ans=res;
alert(ans);
}); // pulls just some of the info from yahoo weather
}
and i've called it on button click in my html file like so:
<button onclick="loadWeather();">View article descriptions</button>
but it doesn't work. i also have the included the source of the javascript file in this document by the way.
You have a function on your node server, but now you'll need to expose it to your client. The simplest way to do this is using the express module.
If you are not completely familiar with node modules and express, there are plenty of startup tutorials available such as https://expressjs.com/en/starter/hello-world.html.
In your case you would need to create an API call that will call the weather data function.
var app = require('express')(),
yw = require('weather-yahoo');
function loadWeather() {
return yw.getSimpleWeather('denver,co');
}
app.get('/weather', function(req, res){
loadWeather().then(function(result){
return res.json(result);
},
function(error){
res.status(400).json(error);
});
});
app.get('/', function(req, res){
res.sendFile(process.cwd() + '/index.html', null, function(err) {
if(err){
res.sendStatus(404);
}
});
})
app.listen(3000, function () {
console.log('Listening on port 3000');
})
This is the simplest of API calls that can easily be extended to return weather for other regions by adding query parameters to the api call.
On the client side, you will now need a function to call your api.
As the example above serves the index file as it's main page, a simple JQuery get call to weather will return the data you want as it is on the same host.
<script>
//This call uses JQuery, make sure you have it referenced in your site
function callAPI() {
$.get("weather", function(data, status){
$('#result').val(JSON.stringify(data));
});
}
</script>
<button onclick="callAPI()">Get Weather</button>
<br>
<textarea id="result" style="width:500px; height:500px"></textarea>
guys.
I want to send a function to browser with socket.io, but failed to do it.
On server side, I response a function with emit, but I get a undefined on browser.
Is there any way to get a function from server with socketio?
there is my code.
// server.js
var static = require('node-static');
var http = require('http');
var file = new(static.Server)();
var app = http.createServer(function(req, res) {
file.serve(req, res);
}).listen(8000);
io = require('socket.io').listen(app);
io.sockets.on('connection', function(socket) {
socket.on('schedule', function() {
console.log('SCHEDULE TASK');
socket.emit('schedule', function() { console.log('hello world'); });
});
});
// client.js
var socket = io.connect('http://localhost:8000');
socket.on('schedule', function(fn) {
fn();
});
socket.emit('schedule');
You cannot send an actual function. You could send a string of Javascript and then you could turn that into a function in the client.
But, I'd suggest you really ought to rethink what you're trying to do here. Generally, the client already has the code it needs (from the script tags that it downloaded) and you send the client data which it then passes to the code it already has or data that it uses to make decisions about which code that it already has to call.
If you show us the real world problem you're trying to solve, we can likely suggest a much better solution than sending a string of Javascript code to the client.
If you really wanted to send a function, you would have to turn it into a string first, send the string, then use the string to turn it back into a function in the client by using a Function object or eval() or creating your own dynamic script tag with inline source.
You can only send strings via socket.io, not functions. That being said, I suggest you to send function names instead.
//server.js
socket.emit('schedule', 'helloworld');
//client.js
function helloworld(){
console.log('hello world');
}
socket.on('schedule',function(name){
window[name](); //hello world
});
I'm having an html file with a hyperlink which calls javascript function.The javascript function has to call a batch file...this all should happen from Node.js
<html>
<head>
<title>sample</title>
<script src="child.js"></script>
</head>
<body>
click here
</body>
</html>
child.js
function call()
{
var spawn = require('child_process').spawn,
ls = spawn('append.bat');
}
I'm getting error like this....
ReferenceError: require is not defined
var spawn = require('child_process').spawn,
any answer..pls reply...
Node.js is a server-side environment for JavaScript. To interact with it from a web page, you'll want to establish an http.Server and use Ajax to communicate between.
A partial example (using a few libraries to simplify) would be:
// server-side
app.post('/append', function (req, res) {
exec('appand.bat', function (err, stdout, stderr) {
if (err || stderr.length) {
res.send(500, arguments);
} else {
res.send(stdout);
}
});
});
// client-side
function call() {
$.post('/append').done(function (ls) {
console.log(ls);
}).fail(function (xhr) {
console.error(xhr.responseText);
});
}
The libraries demonstrated are Express for server-side and jQuery for client-side. It also uses child_process.exec() rather than spawn() to get Buffers rather than Streams.
Resources:
Learn jQuery
Express Guide
SO's node.js Tag Info, which includes a number of "Tutorials, Guides and Books" and "Free Node.js Books and Resources."
You can't access Node.js from browser.
I have the following code and I know that if I use it in the terminal (node test.js, in the case the file is called test.js) but how do I make this code work in javascript with HTML? I mean, how do I make possible to click a button and execute the code? Thank you!
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyACM0", {
baudrate: 9600
}, false);
serialPort.on('error', function(err) {
console.log(err);
});
serialPort.open(function(err) {
if (err) {
console.log(err);
return;
}
console.log('open');
serialPort.on('data', function(data) {
console.log('data received: ' + data);
});
serialPort.write('1', function(err, results) {});
});
}
You can't execute this in a browser (which wouldn't let you access the serial port, for example) but there are various solutions to package some HTML code with nodejs.
The best solution today for a local all-including "desktop-type" architecture is probably node-webkit which has a good support and traction.
Another standard architecture is to simply make nodejs act as a server serving an HTML page including your button. That might be more suited for piloting an Arduino.