Possible to open and write to local files using javascript? - javascript

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

Related

Change video resolution with JS

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")

Adding local file to zip

I'm trying to add a local file to the zip so when the user downloads and unzips, he'll get a folder with a .dll and a config.json file:
var zip = new JSZip();
options.forEach(option => {
zip.folder("REST." + option + ".Connector")
.file("config.json", "//config for " + option)
// I want this file to be from a local directory within my project
// eg. {dir}\custom_rest_connector_repository\src\dlls\Connectors.RestConnector.dll
.file('../dlls/Connectors.RestConnector.dll', null);
});
zip.generateAsync({type:"blob"}).then(function (blob) {
FileSaver.saveAs(blob, "REST_Connectors_"
+ dateStr
+ ".zip");
});
I read through the JSZip documentation but couldn't find an example or any information whether this can actually be done.
If it can't, is there any other more robust library that does support this operation?
Found the answer to my own question using the jszip-utils
JSZipUtils.getBinaryContent("../dlls/Connectors.RestConnector.dll", function (err, data) {
if(err) {
throw err; // or handle the error
}
zip.file("../dlls/Connectors.RestConnector.dll", data, {binary:true});
});

How to make this javascript code run on Windows 8.1?

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)

Create a file in javascript

I want to create a text file in javascript. I have tried this, but it doesn't work:
var file_name=dir+'/aaa.txt';
var fso = CreateObject('Scripting.FileSystemObject');
var s = fsoo.CreateTextFile(file_name, True);
s.Close();
I need to create an empty file to a path.
UPDATE1:
I have also tried this, but doesn't work. Also I can not import System.IO:
var file_name='aaa.txt';
StreamWriter sw = new StreamWriter(file_name);
sw.WriteLine("This is the line");
sw.Close();
UPDATE2:
I also have tryed to execute a unix comand that does 'touch file_name'. However this doesn't work either:
var sys = require('sys')
var exec = require('child_process').exec;
var child;
child = exec(\"touch\" + file_name, function (error, stdout, stderr) {
sys.print('stdout: ' + stdout);
sys.print('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
Does anyone know how I should create a file in javascript?
This project on github looks promising:
https://github.com/eligrey/FileSaver.js
FileSaver.js implements the W3C saveAs() FileSaver interface in
browsers that do not natively support it.
Also have a look at the demo here:
http://eligrey.com/demos/FileSaver.js/
Node.js has a library called FS
FS Tutorial
You can easily create files using a built in function as so,
// include node fs module
var fs = require('fs');
// writeFile function with filename, content and callback function
fs.writeFile('newfile.txt', 'Learn Node FS module', function (err) {
if (err) throw err;
console.log('File is created successfully.');
});

Read and modify HTML from a local file with JavaScript

I can't think of an elegant solution. But, what would be the best way to process an HTML file, modify it and save it back using a script on the command line? I want to basically run this script, proving the HTML file as an argument, add a data-test=<randomID> into every <div> element, and save it back into the file. I was thinking I could write a JavaScript script to execute with node but am not sure how I would get the contents of the provided file, or what to store the content as. Thanks for any pointers.
Solved with jsdom (thanks for the tip, user1600124):
var jsdom = require("jsdom"),
fs = require('fs');
if (process.argv.length < 3) {
console.log('Usage: node ' + process.argv[1] + ' FILENAME');
process.exit(1);
}
var file = process.argv[2];
fs.readFile(file, 'utf8', function(err, data) {
if (err) throw err;
jsdom.env(
data,
["http://code.jquery.com/jquery.js"],
function (errors, window) {
var $ = window.jQuery;
$("p, li").each(function(){
$(this).attr("data-test", "test");
});
$(".jsdom").remove();
console.log( window.document.doctype + window.document.innerHTML );
var output = window.document.doctype + window.document.innerHTML;
fs.writeFile(file, output, function(err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
});

Categories

Resources