How to append to certain line of file? - javascript

I want to append to a file but I want to start appending before </xml> tag end. appears. How can I do that?
var fs = require("fs");
fs.appendFile('somefile.xml', 'Content')
I have sth like this but it insert 'content' at the end of file, and I want it in specific line before specific 'keyword'

This might not be the easiest option, but at least it should get the job done. Haven't tested it, so it might require some changes. It reads the file and when it's done, it creates the new file by removing the </xml> tag, adding the content and then adding the </xml> tag again at the end.
var fs = require('fs');
var xmlFile;
fs.readFile('someFile.xml', function (err, data) {
if (err) throw err;
xmlFile = data;
var newXmlFile = xmlFile.replace('</xml>', '') + 'Content' + '</xml>';
fs.writeFile('someFile.xml', newXmlFile, function (err) {
if (err) throw err;
console.log('Done!');
});
});

A good approach is to split the file into a wrapper file and a body file. The wrapper just contains the outermost tag and an entity reference to the body file. Your program can then append to the end of the body file, whereas anyone reading the file as XML should read the wrapper file. The wrapper file will look something like this:
<!DOCTYPE xml [
<!ENTITY e SYSTEM "body.xml">
]>
<xml>&e;</xml>
Using "xml" as an element name, by the way, is bad practice. All names starting "xml" are reserved for future use by W3C.
This approach may not work if you're reading the XML in a browser. I think that some browsers' XML parsers don't support external entities.

Related

Import HTML to dynamically add elements using JS

I will be dynamically adding elements to my main index.html using .innerHTML += "<p>example</p>"; However I do not want to store the large html-like string in this .js file, but instead import it from another file example.html
example.html:
<p>example</p>
(It is just a snippet of code and not a standalone html file, but I want to keep the .html extension for linting, autocompletion and general readability)
My attempts:
$(...).load('example.html'): did not work as it replaces of contents of ... with this example instead of appending it
import * from example.html: this and other attempts of importing file failed because of MIME error that text/html cannot be imported
I will be perfectly satisfied with a solution of a method that reads .html as text and returns it as a string (preferably not using AJAX or ES6 as I do not feel confident with them). I would then just use the string in .innerHTML += imported_string; and call it a day.
If I correctly understand what you want to do, you can use FileReader to import the content of a file and convert it to text, for example:
function readFile(event) {
var file = event.target.files[0];
var stream = new FileReader();
stream.onload = function(e) {
var fileContent = e.target.result;
alert(fileContent);
}
stream.readAsText(file);
}
document.getElementById('myFile').addEventListener('change', readFile, false);
<input type="file" accept="html" id="myFile">
The file input is for presentation purposes, you can easily adapt this to your needs.
You should also perform the customary checks, which I ommited for brevity purposes.
Create a fetch request to the file that you want to retrieve. This is, in a basic sense, the same way how a browser would request a html file from the server.
The function below sends a request based on what you input as a file. For example, 'example.html'. It then checks if the request was a success and returns the response as a string. The string can then be appended to your innerHTML.
const getFileAsText = async file => {
const response = await fetch(file);
if (!response.ok) {
throw new Error(`Fetching the HTML file went wrong - ${response.statusText}`);
}
return response.text();
};
You can use it like the example below.
getFileAsText('example.html').then(html => {
document.body.innerHTML += html;
});

Create File object without saving

I'm trying to look for a way to create a .txt File object without saving it to disk in Node.js. In browser I'd do something like
new File(['file_contents'], 'file_name.txt', {type: 'text/plain'})
The end aim is to create a .txt file object temporarily for my Discord Bot to send as a message attachment.
From the discord.js documentation, I presume I'm supposed to create a Buffer or Stream object representing the file.
I'm already using require('node-fetch') library to read attachments in messages, if that has any relevancy (but can't see anything in their docs on this either).
After playing around in console I've found Buffer.from('string of txt file contents') to represent the file seems to work fine.
Usage:
channel.send(new Discord.MessageAttachment(Buffer.from('Hello World'), 'file_name.txt'))
In order to write a text file in JS you should use the fs library, included in Node.js.
Here is an example of writing to a file:
fs = require('fs');
let content = "Hello world!";
fs.writeFile('file.txt', content, function (err) {
if (err) return console.log(err);
// Code here will execute if successfully written
});
Then in order to send a local file to Discord you can use .send with an object containing a files property in it, like this:
channel.send({
files: [{
attachment: 'entire/path/to/file.txt',
name: 'file.txt'
}]
}).then(() => {
// Delete file
fs.unlink('file.txt');
});
You can see more about .send() here and you can find more about the fs module here

NodeJS - How to insert an element in a HTML document using Javascript?

I'm trying to use NodeJS to modify an external HTML file (which is located in the same directory). In my index.js file I write:
fs.readFile('index.html', (err,html)=>{
if(err){
throw err;
}
html.body.innerHTML += '<div id = "asdf"></div>';
});
As index.html is a valid document. But it doesn't look to be reading it properly, as I get as an error:
"TypeError: Cannot read property 'innerHTML' of undefined".
I guess that html is not getting anything as body.
How can I do changes in HTML using JavaScript?
Here is an example using node-html-parse
HTML file
<html>
<body>
<div id="fist">yolo</div>
</body>
</html>
And the nodejs
const fs = require('fs');
const parse = require('node-html-parser').parse;
fs.readFile('index.html', 'utf8', (err,html)=>{
if(err){
throw err;
}
const root = parse(html);
const body = root.querySelector('body');
//body.set_content('<div id = "asdf"></div>');
body.appendChild('<div id = "asdf"></div>');
console.log(root.toString()); // This you can write back to file!
});
There might be better solutions than node-html-parser, considering the amount of downloads. For example, htmlparser2 has much more downloads, but it also looks more complex :)
In order to manipulate an html file the way you'd be able to in a browser, you'll first need to parse it.
Perhaps node-html-parser can be of use? (Or if a few milliseconds of parsing are not a concern and you want some more functionality, the JSDOM package is very popular too.)
innerHTML is a function provided after DOM parsing. Here you are using a string, so you can either use a DOM parser to create the structure or you can just use regex to isolate the part you want to replace and append the text.
html.replace("</body>",'<div id = "asdf"></div></body>');

fs.write json file to capture and save streaming json file

I want json stream stored in text file. When running the node server, the json file isn't appended to the json.txt file. What am I missing? Am new to to node, so be gentle..
Here is a code chunk I expect to capture the json content:
var fs = require('fs');
fs.writeFile("json.txt",{encoding:"utf8"}, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
The issue is you aren't using the correct parameters. When calling fs.writeFile it expects a string for the filename, a buffer or string for the content, an object for the options and a callback function. What it looks like you're doing is sending the options as the second parameter when it expects a buffer or a string. Correction below;
var fs = require('fs');
fs.writeFile("json.txt", JSON.stringify({some: object}), {encoding:"utf8"}, function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
You can replace the JSON.stringify part with some plain text if you wanted to, but you specified JSON in your question so I assumed you wanted to store some object in a file
Source (NodeJS documentation)
EDIT:
The links to other questions in the comments may be more relevant if you want to add new lines to the end of the file and not completely overwrite the old one. However I made the assumption that fs.writeFile was the intended function. If that wasn't the intention, those other questions will help a lot more
UPDATE:
It seems the issue was the fact that the body wasn't being parsed, so when the POST request was going through, Node didn't have the request body. To alleviate this, during the express configuration, the following code is needed:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
Uses the npm module body-parser. This will convert the JSON body to a JavaScript object, and it is accessible via req.body.

How to edit File in perfoce with node js?

If i have the code below how can i edit the specific file and make the right corrections?
var p4 = require('C:/Program Files/nodejs/node_modules/p4');
var File = process.argv[2];
p4.edit(File, function(err, data) {
if (err) {
console.error(err.message);
}
console.log(data);
});
Your code looks correct to open the file for edit. If that returns any errors when you run it, you should post those here, but I'll assume that it returns a success message ("(file) opened for edit").
Opening the file for edit means that it is made writable on the local filesystem (i.e. the one where this code is running -- the file is the one you passed as an argument to the edit command). To actually modify the file you can use any other function at your disposal.

Categories