This is a piece of code used to import subscriptions from one Youtube account to another by opening up a new Google Chrome tab/window with a channel url from the list inside the downloaded subscription_manager.xml file. When I use node to open the "app.js" file it shows no errors but it never opens Chrome. I think because the creator of the code was using Mac Os, he may have written something that isn't compatible in Windows. Can someone verify this to make sure it works for Windows too? Link to video "https://youtu.be/GVakGPDF3Kc"
var fs = require('fs'),
childProcess = require('child_process'),
xml2js = require('xml2js');
var parser = new xml2js.Parser();
fs.readFile(__dirname + '/subscription_manager.xml', function (err, data) {
parser.parseString(data, function (err, result) {
var nodes = result.opml.body[0].outline[0].outline;
nodes.forEach(function (node, index) {
var url = node['$'].xmlUrl;
url = url.substring(url.indexOf('=') + 1, url.length);
var channel = 'https://www.youtube.com/channel/' + url;
if (index == 1) {
childProcess.exec('open -a "Google Chrome" ' + channel);
}
});
});
});
You're right about the MacOS vs Windows portion - this code:
childProcess.exec('open -a "Google Chrome" ' + channel);
is for the MacOS terminal. You could try changing it to:
childProcess.exec('start chrome ' + channel);
(Tested on Windows 10)
Related
I'm developing a video storage service for users and I need that large videos (v.g. 4K) can be compressed to 1080p before saving them. Is there a JS library (browser or Node) that helps with this task? Maybe a webservice?
I also accept language suggestions.
When it comes to downscaling video, the most accessible option is ffmpeg.
There is a package that makes using ffmpeg in node.js easier: https://www.npmjs.com/package/fluent-ffmpeg
For example, downscaling a video to 1080p and 720p:
var ffmpeg = require('fluent-ffmpeg');
function baseName(str) {
var base = new String(str).substring(str.lastIndexOf('/') + 1);
if(base.lastIndexOf(".") != -1) {
base = base.substring(0, base.lastIndexOf("."));
}
return base;
}
var args = process.argv.slice(2);
args.forEach(function (val, index, array) {
var filename = val;
var basename = baseName(filename);
console.log(index + ': Input File ... ' + filename);
ffmpeg(filename)
.output(basename + '-1280x720.mp4')
.videoCodec('libx264')
.size('1280x720')
.output(basename + '-1920x1080.mp4')
.videoCodec('libx264')
.size('1920x1080')
.on('error', function(err) {
console.log('An error occurred: ' + err.message);
})
.on('progress', function(progress) {
console.log('... frames: ' + progress.frames);
})
.on('end', function() {
console.log('Finished processing');
})
.run();
});
(source: https://gist.github.com/dkarchmer/635496ff9280011b3eef)
You don't need any node packages to run ffmpeg, you could make use of the child_process API in node.js.
The ffmpeg package has to be installed on the server that will be running your application.
.format("h264") √
.format("mp4") ×
or add
.outputOptions(['-movflags isml+frag_keyframe'])
.format("mp4")
I want to use webrtc in an IOS (Swift) project. I find so much difficulties to implement it properly. So I searched for an library so I can get how it is implemented to do it later myself.
I found this project:
https://github.com/sushilthe/webrtc-ios-swift
It works fine with https://apprtc.appspot.com. But it is making a POST? request when you want to join a room:
Base url:
https://apprtc.appspot.com/
Part that is appended to the base:
static NSString *kARDRoomServerRegisterFormat =
#"%#/join/%#";
Result:
https://apprtc.appspot.com/join/'roomnr'
I have build a server with some resources from the internet:
$(document).ready(function() { //wait for DOM to be ready for JS execution
easyrtc.setVideoDims(1280, 768);
easyrtc.easyApp('vcdemo', 'self', ['peer'], connectSuccess, failureCallback); //connect to easyrtc app; initiate media sources and elements
});
//global state variables
var myEasyrtcId; //id of client in the signaling framework
//global functions
var connectSuccess = function(easyrtcid) { //join room as defined by "room" parameter in URL
myEasyrtcId = easyrtcid;
console.log('Connect successful. My id is ' + myEasyrtcId + '.');
var room = decodeURIComponent((new RegExp('[?|&]room=' + '([^&;]+?)(&|#|;|$)'). //retrieve room name from URL
exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;
console.log('join room: ' + room);
easyrtc.joinRoom(room, null, joinSuccess, failureCallback);
};
var failureCallback = function(errorCode, errorMsg) { //log error
console.log(errorCode);
console.log(errorMsg);
};
var joinSuccess = function(roomName) { //listen for peers joining the room
setTimeout(function() {
console.log('successfully joined room: ' + roomName);
var peers = easyrtc.getRoomOccupantsAsArray(roomName) || []; //get list of client connected to room
console.log('peers: ' + peers);
var peersLength = peers.length;
if (peersLength > 2) { //support only 1-1 video conferences
alert('The meeting room is already full. ' +
'Only the two peers connecting first will be allowed access.');
} else if(peersLength === 1) { //if no other peer is connected
console.log('waiting for peer to connect...');
} else if(peers[0] != myEasyrtcId) {//get peer id
easyrtc.call(peers[0]);
} else {
easyrtc.call(peers[1]);
}
}, 100);
};
This works perfect in chrome and firefox via this url:
localhost:8080/?room=123
And I can connect to that stream when I reuse that room number. Perfect!
So I thought I can implement that in the app, I have changed the serverHostUrl to: client?.serverHostUrl = "192.168.1.59:8080"
And the other variable:
static NSString *kARDRoomServerRegisterFormat = #"%#/?room=%#";
But I get an error when it try's to submit the url:
Client Connecting
2016-10-17 19:24:51.151795 WebRTC iOS Swift[3944:1036130] Registering with room server.
2016-10-17 19:24:51.151900 WebRTC iOS Swift[3944:1036130] url = 192.168.1.59:8080/?room=123
2016-10-17 19:24:51.207496 WebRTC iOS Swift[3944:1036130] Error posting data: unsupported URL
Client Disconnected
I have searched a few hours why this is happening. But I can't find the problem. Thank you very much!
EDIT
The Code where it goes wrong:
The roomURL is: 192.168.1.59:8080/?room=123 at that moment.
[NSURLConnection sendAsyncPostToURL:roomURL
withData:nil
completionHandler:^(BOOL succeeded, NSData *data) {
ARDAppClient *strongSelf = weakSelf;
if (!succeeded) {
NSError *error = [self roomServerNetworkError];
[strongSelf.delegate appClient:strongSelf didError:error];
completionHandler(nil);
return;
}
ARDRegisterResponse *response =
[ARDRegisterResponse responseFromJSONData:data];
completionHandler(response);
}];
I've been trying this for a while, but I keep getting the error:
Error: Command failed: Invalid Parameter - /images
I installed ImageMagick and the gm package, so that's definitely not the problem.
gm(imageLocation)
.resize(100) // use your own width and height
.write('here.jpg', function (err) {
if (!err) console.log(' hooray! ');
else console.log(err);
});
imageLocation being ./images/3.jpg. Why does this error keep happening? I looked at the documentation
I'm on a Windows 32 bit machine. My server is supposed to get an image from a folder, resize it, and then display it. It seems like I have to write the resized photo and then display that, but the writing process always errors out and the image ends up being empty.
If there's a way to skip the writing part and just displaying the photo directly, that would be awesome too.
Thanks!
URL Query I used: http://localhost:8123/images/3.jpg
Complete code:
var querystring = require('querystring'); //used for parsing parts of urls
url = require('url');
http = require('http');
fs = require('fs');
gm = require('gm').subClass({ imageMagick: true });;
var server = http.createServer();
server.on('request', function(request, response){
var parsed_url = url.parse(request.url, true); //true gets the query as well
imageLocation = '.' + parsed_url.pathname;
gm(imageLocation)
.resize(100) // use your own width and height
.write('here.jpg', function (err) {
if (!err) console.log(' hooray! ');
else console.log(err);
});
if (getImage('here.jpg', response)){
//image is displayed
}
else{
respond404(parsed_url.pathname, response);
}
})
function respond404(path, response){
respond(404, "The requested path " + path + " was not found", response)
}
function getImage(location, response)
{
try{
var img = fs.readFileSync(location);
response.writeHead(200, {'Content-Type':'image/jpg'}); //parse this end
response.end(img, 'binary');
return true;
}catch(e){
return false;
}
}
server.listen(8123);
The answer Svbaker put can be used in Linux (maybe Mac as well?)
For Windows I got it to work by opening the command line in administrator mode and starting my server there.
I was able to get your code to work by changing how you required gm as follows:
var gm = require('gm');
I also had to remember to execute node with the correct permissions in my case:
sudo node server.js
At work I have to repeat this same process multiple times:
Open a certain Dreamweaver file.
Look for all <p> tags and replace then with <h1> tags.
Look for all </p> and replace with </h1>.
Look for the string 'Welcome' and replace with 'goodbye'.
Look for '0:01:00' and replace with '01:00'.
Copy everything in that file.
Create a new Dreamweaver file and paste everything in the new file.
Save the new file in a given directory and call it a certain name, which can be provided as a variable.
I don't need to run the JavaScript from a browser. It can be a JavaScript file which I just double click on the desktop.
Is it possible for me to do this with JavaScript / jQuery?
There are many other programming languages that you could accomplish this task with but if you really want to use Javascript then you could do the following:
var fs = require('fs');
if(process.argv.length < 4) {
console.log('Usage: node replace.js fromFilePath toFilePath');
return;
}
from = process.argv[2];
to = process.argv[3];
fs.readFile(from, { encoding: 'utf-8' }, function (err, data) {
if (err) throw err;
console.log('successfully opened file ' + from);
var rules = {
'<p>': '<h1>',
'</p>': '</h1>',
'Welcome': 'goodbye',
'0:01:00': '01:00'
};
for(var index in rules) {
console.log('Replacing ' + index + ' with ' + rules[index] + '...');
data = data.replace(new RegExp(index, 'gi'), rules[index]);
console.log('Done');
}
console.log("Result");
console.log(data);
console.log("Writing data to " + to);
fs.writeFile(to, data, function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
INSTRUCTIONS
Download node.js from here
Install it
Create a file in C:\replace.js (Win) or ~/replace.js (Mac OS)
Put the code from above in replace.js
Open cmd (Ctrl+R on Win) or Terminal (on Mac OS)
Type node C:\replace.js <fileToReadFrom> <fileToSaveTo> on Win or node ~/replace.js <fileToReadFrom> <fileToSaveTo> on Mac OS
Done
Right now I'm using this script in PHP. I pass it the image and size (large/medium/small) and if it's on my server it returns the link, otherwise it copies it from a remote server then returns the local link.
function getImage ($img, $size) {
if (#filesize("./images/".$size."/".$img.".jpg")) {
return './images/'.$size.'/'.$img.'.jpg';
} else {
copy('http://www.othersite.com/images/'.$size.'/'.$img.'.jpg', './images/'.$size.'/'.$img.'.jpg');
return './images/'.$size.'/'.$img.'.jpg';
}
}
It works fine, but I'm trying to do the same thing in Node.js and I can't seem to figure it out. The filesystem seems to be unable to interact with any remote servers so I'm wondering if I'm just messing something up, or if it can't be done natively and a module will be required.
Anyone know of a way in Node.js?
You should check out http.Client and http.ClientResponse. Using those you can make a request to the remote server and write out the response to a local file using fs.WriteStream.
Something like this:
var http = require('http');
var fs = require('fs');
var google = http.createClient(80, 'www.google.com');
var request = google.request('GET', '/',
{'host': 'www.google.com'});
request.end();
out = fs.createWriteStream('out');
request.on('response', function (response) {
response.setEncoding('utf8');
response.on('data', function (chunk) {
out.write(chunk);
});
});
I haven't tested that, and I'm not sure it'll work out of the box. But I hope it'll guide you to what you need.
To give a more updated version (as the most recent answer is 4 years old, and http.createClient is now deprecated), here is a solution using the request method:
var fs = require('fs');
var request = require('request');
function getImage (img, size, filesize) {
var imgPath = size + '/' + img + '.jpg';
if (filesize) {
return './images/' + imgPath;
} else {
request('http://www.othersite.com/images/' + imgPath).pipe(fs.createWriteStream('./images/' + imgPath))
return './images/' + imgPath;
}
}
If you can't use remote user's password for some reasons and need to use the identity key (RSA) for authentication, then programmatically executing the scp with child_process is good to go
const { exec } = require('child_process');
exec(`scp -i /path/to/key username#example.com:/remote/path/to/file /local/path`,
(error, stdout, stderr) => {
if (error) {
console.log(`There was an error ${error}`);
}
console.log(`The stdout is ${stdout}`);
console.log(`The stderr is ${stderr}`);
});