Read and modify HTML from a local file with JavaScript - 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!');
});
});
});

Related

Trying to create a new file by copying data of a variable

Trying to create a new csv file in a directory.
I want to store the data of a variable inside that csv file:
handleRequest(req, res) {
var svcReq = req.body.svcReq;
var csvRecData = JSON.stringify(req.body);
console.log("DATA WE ARE GETIING IS: " + csvRecData);
if (svcReq == 'invDetails') {
var checking = fs.writeFile('../i1/csvData/myCsvFile.csv', csvRecData, function (err) {
if (err) throw err;
console.log("Saved! got the file");
console.log("Checking csvData:" + checking);
});
}
}
I don't see any errors in the console or terminal but the file is not generated. What is my issue?
The path in writeFile should be pointed correctly..you cannot simply use "../il/csv" from your current file.First check your current directory using path.
1)Install path npm module
2)
var path = require('path');
var fs = require('fs');
console.log(path.join(__dirname))
fs.writeFile((path.join(__dirname)+"/test123.csv"), "Sally Whittaker,2018,McCarren House,312,3.75!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});

How to recursively read file in a tree like directory structure in node js

I have a root directory say "A" inside this directory i am having lots of directories say "1","2","3","4","5"........ and in all these subdirectories i have single file called cucumber.json. All i want to do is read the cucumber.json file and get the accumulated result. How can i achieve this using node js.
In the below screen shot my root directory is "cucumber" and inside that i have lot of sub directories. All these sub directories contains a single file named cucumber.json.
Are there any dedicated node package which can make my work easy.
Let me know if any further info is required.
Hi there please try the following (javascript):
// Require filesystem package for IO operations
var fs = require('fs');
// Put the path you are looking for here
var path = "d:\\nodef";
//Call the function defined below
recursiveloop(path, function(err,result){
/* begin processing of each result */
// For each file in the array
for(i=0;i<result.length;i++)
{
//Write the name of the file
console.log('Processing: ' + result[i]);
//Read the file
fs.readFile(result[i], 'utf8', function(err, data){
//If there is an error notify to the console
if(err) console.log('Error: ' + err);
//Parse the json object
var obj = JSON.parse(data);
//Print out contents
console.log('Name: ' + obj.name);
console.log('Position: ' + obj.position);
})
}
});
// Asynchronous function to read folders and files recursively
function recursiveloop(dir, done)
{
var results = [];
fs.readdir(dir, function(err, list){
if (err) return done(err);
var i = 0;
(function next() {
var file = list[i++];
if (!file) return done(null, results);
file = dir + '/' + file;
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
recursiveloop(file, function(err, res) {
results = results.concat(res);
next();
});
} else {
results.push(file);
next();
}
});
})();
});
}

Reading file to disk error, "name and value are required for setHeader()"

Trying to allow users to upload image files to the Node.js server in a MEAN Stack application. I am using ng-file-upload for the client side angular directive. That seems to be working good enough. I run into an error when I pass the image to the server.
I use an API route to handle the work on the server side. The server will be responsible for saving the file to disk with node-multiparty module. It seems to hit route but when it tries to emit a close event I get the error. throw new Error('"name" and "value" are required for setHeader().'
The file I want is in my temp folder but it doesn't get saved to the target directory on my server plus I get the header error after the file should have been saved. So I need to stop the error and save the file with fs.rename() to the target image directory.
Here is the code that is breaking.
file api.js
// router to save images
router.route('/img/upload')
.post(function (req, res) {
console.log("image upload hits the router")
var options = {};
var count = 0;
var form = new multiparty.Form(options);
//save file to disk
form.on('file', function (name, file) {
var uploadDirectory = 'img/user/profile/';
var oldPath = file.path;
var newPath = uploadDirectory + file.originalFilename;
fs.rename(oldPath, newPath, function (err) {
if (err) throw err;
console.log('renamed complete');
});
});
// Close emitted after form parsed
form.on('close', function () {
console.log('Upload completed!');
res.setHeader('text/plain'); // Here is the line that gives an error.
res.end('Received ' + count + ' files');
});
// Parse req
form.parse(req);
});
So this is what I got to work for me
The actual line that gave me an error was setHeaders. It appears I needed to put the name and value as strings separated by a comma. This works perfectly for me now. I hope it saves everyone time coding.
// post
.post(function (req, res) {
var options = {};
var count = 0;
var form = new multiparty.Form(options);
form.on('error', function (err) {
console.log('Error parsing form: ' + err.stack);
});
//save file to disk
form.on('file', function (name, file) {
var uploadDirectory = '/img/user/profile/';
var oldPath = file.path;
var newPath = uploadDirectory + file.originalFilename;
fs.rename(oldPath, newPath, function (err) {
if (err) throw err;
console.log('renamed complete');
});
});
// Close emitted after form parsed
form.on('close', function () {
console.log('Upload completed!');
res.setHeader('Content-Type', 'text/plain');
res.end('Received ' + count + ' files');
});
// Parse req
form.parse(req);
});

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.');
});

Possible to open and write to local files using 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

Categories

Resources