My project structure looks like
js
/client.js
/script1.js
/webWoker.js
node_modules
.gitignore
index.html
The main.html has it included as well in
<script type="text/javascript" src="js/script1.js"></script>
<script type="text/javascript" src="js/client.js"></script>
<script type="text/javascript" src="js/webWoker.js"></script>
My script1.js looks like
if (window.Worker) {
console.log("uri: " + document.documentURI);
var myWorker = new Worker("myworker.js");
myWorker.postMessage("hello");
console.log(myWorker);
myWorker.onmessage = function (e) {
result.textContent = e.data;
console.log('Message received from worker: ' + result.textContent);
};
}
and my webWorker.js looks like
onmessage = function (e) {
console.log('Message received from main script');
var result = "#27ae60";
console.log('Posting message back to main script');
postMessage(result);
};
I use node.js for this project and run it via npm start, and when I run this in browser I see
script1.js:81 GET http://localhost:8080/webWorker.js 404 (Not Found)
execute # script1.js:81
img.onload # script1.js:64
What is going wrong here?
You don't have to include the worker script in your main page (it's even a bad idea), but the URI you pass to new Worker(URI) is relative to the current documentURI.
So in your case, it should be new Worker("/js/webWorker.js");.
Related
I am trying to make a very simple html with local server that displays all images in a local directory (content folder). But I am getting jquery-3.2.1.min.js:4 GET http://localhost:8080/content/ 404 (Not Found)
So, my file structure looks like:
rootfolder
-content/
-js/
-index.html
-server.js
server.js looks like this:
var connect = require('connect')
var serveStatic = require('serve-static')
connect().use(serveStatic(__dirname)).listen(8080, function () {
console.log('Server running on 8080...')
console.log('dirname', __dirname)
})
index.html like this:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div id="img-container">
</div>
</body>
</html>
index.js looks like this:
window.onload = function () {
var folder = 'content/'
$.ajax({
url: folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if (val.match(/\.(jpe?g|png|gif)$/)) {
$("body").append( "<img src='"+ folder + val +"'>" )
}
})
}
})
console.log('test2')
}
The code isn't very clean at the moment but I want to figure out why I am getting 404 Not Found error first.
I'm having issues with developing my Google Chrome extension. I need some specific npm modules in order to execute my code so I looked into Browserify. I followed all the steps without issue but the code still produces errors when run. The screenshot is attached below.
Error when Chrome extension is only loaded
All my files are located in the same project folder (popup.html, popup.js, bundle.js, etc.). I only have one html file and one javascript file (excluding bundle.js).
Here is my popup.html code:
document.addEventListener('DOMContentLoaded', function() {
var convertMP3Button = document.getElementById("getLinkAndConvert");
convertMP3Button.addEventListener("click", function() {
chrome.tabs.getSelected(null, function(tab) { // 'tab' has all the info
var fs = require('fs');
var ytdl = require('ytdl-core');
var ffmpeg = require('fluent-ffmpeg');
var ffmetadata = require("ffmetadata");
var request = require('request');
console.log(tab.url); //returns the url
convertMP3Button.textContent = tab.url;
var url = tab.url;
var stream = ytdl(url);
//.pipe(fs.createWriteStream('/Users/nishanth/Downloads/video.mp4'));
// Helper method for downloading
var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};
ytdl.getInfo(url, function(err, info) {
console.log("INFO: " + JSON.stringify(info, null, 2));
var process = new ffmpeg({source:stream})
process.save('/Users/nishanth/Downloads/' + info.title + '.mp3').on('end', function() {
console.log("PROCESSING FINISHED!");
download(info.thumbnail_url, "/Users/nishanth/Downloads/image.jpg", function() {
console.log("DOWNLOADED IMAGE");
var options = {
artist: info.author,
attachments: ["/Users/nishanth/Downloads/image.jpg"]
};
ffmetadata.write('/Users/nishanth/Downloads/' + info.title + '.mp3', {}, options, function(err) {
if (err)
console.error("Error writing cover art: " + err);
else
console.log("Cover art added");
});
});
});
});
});
});
});
<!doctype html>
<html>
<head>
<title>Youtube Music</title>
<script src="bundle.js"></script>
<script src="popup.js"></script>
</head>
<body>
<h1>Youtube Music</h1>
<button id="getLinkAndConvert">Download Song Now!</button>
</body>
</html>
It would be great if I could find out the reason why I have not been able to properly integrate browserify in order to use the npm modules.
Browsers don't allow you to access the file system, instead they usually have some storage mechanisms of their own (cookies, localstorage, or a browser-specific system like chrome.storage). Browserify has no way of getting around this, and doesn't provide a shim for require('fs'). Instead of writing directly to disk you'll need to have your app provide a downloadable version of your files, which the user will then have to save manually. If you don't need the files to be accessible outside the extension you can use the api I linked earlier, or drop in something like browserify-fs which creates a virtual file system in the browser's storage.
When I execute the following code, I get the error: Reference Error: Watershed is not defined. How can I define it? Do I need a module to be installed for it?
var restify=require('restify');
var ws= new Watershed();
var server=restify.createServer();
server.get('websocket/attach', function upgradeRoute(req, res, next){
if(!res.claimUpgrade){
next(new Error("Connection must be upgraded."));
return;
}
var upgrade=res.claimUpgrade();
var shed=ws.accept(req, upgrade.socket, upgrade.head);
shed.on('text', function (msg){
console.log("The message is: "+msg);
});
shed.send("hello there");
next(false);
});
server.listen(8081, function(){
console.log('%s listening at %s', server.name, server.url);
});
There is also a section of the restify doc that mentioned how to handle the ability to upgrade sockets. I just struggled with this for an emarrassingly long time and thought I'd share the simple solution. In addtion the #Dibu Raj reply, you also need to create your restify server with the handleUpgrades option set to true. Here is a complete example to make restify work with websocket upgrades and watershed:
'use strict';
var restify = require('restify');
var watershed = require('watershed');
var ws = new watershed.Watershed();
var server = restify.createServer({
handleUpgrades: true
});
server.get('/websocket/attach', function (req, res, next) {
if (!res.claimUpgrade) {
next(new Error('Connection Must Upgrade For WebSockets'));
return;
}
console.log("upgrade claimed");
var upgrade = res.claimUpgrade();
var shed = ws.accept(req, upgrade.socket, upgrade.head);
shed.on('text', function(msg) {
console.log('Received message from websocket client: ' + msg);
});
shed.send('hello there!');
next(false);
});
//For a complete sample, here is an ability to serve up a subfolder:
server.get(/\/test\/?.*/, restify.serveStatic({
directory: './static',
default: 'index.html'
}));
server.listen(8080, function() {
console.log('%s listening at %s', server.name, server.url);
});
For an html page to test your new nodejs websocket server: write this html below into a file at ./static/test/index.html - point your browser to http://localhost:8080/test/index.html - open your browser debug console to see the message exchange.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Web Socket test area</title>
<meta name="description" content="Web Socket tester">
<meta name="author" content="Tim">
</head>
<body>
Test Text.
<script>
(function() {
console.log("Opening connection");
var exampleSocket = new WebSocket("ws:/localhost:8080/websocket/attach");
exampleSocket.onopen = function (event) {
console.log("Opened socket!");
exampleSocket.send("Here's some text that the server is urgently awaiting!");
};
exampleSocket.onmessage = function (event) {
console.log("return:", event.data);
exampleSocket.close();
}
})();
</script>
</body>
</html>
Your browser log will look something like this:
07:05:05.357 index.html:18 Opening connection
07:05:05.480 index.html:22 Opened socket!
07:05:05.481 index.html:26 return: hello there!
And your node log will look like:
restify listening at http://[::]:8080
client connected!
Rest service called started
upgrade claimed
Received message from websocket client: Here's some text that the server is urgently awaiting!
Documentation for this found at:
http://restify.com/#upgrade-requests
You should include the watershed library
var Watershed = require('lib/watershed').Watershed;
I have the following code below :
<!DOCTYPE html>
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207",{}, function(user){
console.log("in the function w/ " + user);
});
</script>
</head>
</html>
The code should print the user name to the console however whenever I run this, my console gives the error of :
Failed to load resource: The requested URL was not found on this server:
file://api.soundcloud.com/users/3207?client_id=f520d2d8f80c87079a0dc7d90db9afa9&format=json&_status_code_map%5B302%5D=200
However if I were to directly http://api.soundcloud.com/users/3207.json?client_id=f520d2d8f80c87079a0dc7d90db9afa9, then I get a valid JSON result.
Is there something incorrect with my how I am using the SC.get function?
Thanks
Well, you should test your index.html locally on a web-server like Apache and not by opening it as a file.
Working example
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207", {}, function(user) {
console.log("in the function w/ " + JSON.stringify(user));
var res = document.getElementById("result");
res.innerHTML = JSON.stringify(user);
});
<script src="http://connect.soundcloud.com/sdk.js"></script>
<div id="result"></div>
I was following along the tutorial at http://nowjs.com/doc when I encountered some errors.
<html>
<head>
<title>index.html</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"/>
<script src="http://localhost:8080/NowJS/now.js"></script>
<script>
$(document).ready(function(){
var name = prompt("what is your name?","");
now.receiveMessage = function(name,message){
alert(name+" "+message);
};
$('.butt').click(function(){
alert($('#put').val());
now.distributeMessage(name,$('#put').val());
$('#put').val('');
});
});
</script>
and for the server:
var fs = require('fs');
var sys = require('sys');
var server = require('http').createServer(function(req,response){
fs.readFile('index.html',function(err,data){
response.writeHead(200);
response.write(data);
response.end();
});
});
server.listen(8080);
sys.print('woot');
var everyone = require('now').initialize(server);
everyone.now.distributeMessage = function(name, message){
sys.print(name+" "+message);
everyone.now.receiveMessage(name,message);
};
I highly suspect it has something to do with my tag since there isnt anything at /NowJS/now.js.
Can someone enlighten me on this part:
On pages that you would like to use NowJS on, simply include this script tag in your HTML head: NowJS only works on pages that are served through the same http server instance that was passed into the initialize function above.
Thanks for your time.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"/>
script tags can't be self-closed.
In the docs the path in the script tag is lower-case, /nowjs/now.js, whereas in your snippet it is /NowJS/now.js, and so I guess this is the reason it doesn't work.