How can I edit file in JavaScript? - javascript

I want to be able to:
-edit the data of a .dat file on my computer for a website.
-pull data from the file to use it later on.
I know a tiny bit about javascript and heard javascript cannot directly edit databases.
Is a .dat file in my computer a database?
I have done a few things in Javascript for websites but I haven't done anything complicated completely myself. I created some websites before and I have a basic understanding of HTML and CSS.
Please phrase your response as simply as possible. Explain the meaning of any complicated but necessary terms.

You need some server-side script to access the filesystem of the server such as PHP or NodeJs...
Nodejs example here.
let fs = require('fs');
Appeding file:
fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
Delete file:
fs.unlink('mynewfile2.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
Read file :
fs.readFile('demofile1.html', function(err, data) {
if (err) throw err;
console.log(data);
});

Related

Node.js/Azure: upload HTML to BlobStorage

I have a frontend which sends the HTML of that page to a Node.js server. The server should then send that HTML to Azure BlobStorage.
Here is my express route to handle this:
router.post("/sendcode", function(req, res) {
let code = "";
code = req.body.code;
console.log(code);
let service = storage.createBlobService(process.env.AccountName, process.env.AccountKey);
service.createContainerIfNotExists("htmlcontainer", function(error, result, response) {
if (error) {
throw error;
} else {
service.createBlockBlobFromStream("htmlcontainer", code, function(err, result, response) {
if (err) {
throw err;
} else {
console.log(result);
console.log(response);
}
});
}
});
});
When I call this route, I receive this in my console:
<html><style>* { box-sizing: border-box; } body {margin: 0;}</style><body></body></html>
How can I send it to BlobStorage? Avoid the method I used as it maybe wrong because I can't figure out what function to use because of scarce documentation.
There are many answers on stack overflow, you can follow this one and adjust it to your needs:
Uploading a file in Azure File Storage using node.js
So after trying a little bit, i was able to send it not from stream but after writing it to a file, sending that file through createBlockBlobFromLocalFile function in azure-storage module and deleting the file from disk.
I know this isnt the most efficient method out there but it got my work done.
The problem i was facing was that after uploading html code in a block blob(without file operation), its content type was application/octet which i wanted to be text/html. So i had to perform one more operation to change its content type, which i found to be a little difficult due to unavailability of documentation and examples in javascript.

Files is deleting before its used in node js

I'm new to node js and i'm trying to do the following:
function createPasswordfile(content)
{
fs.writeFile(passwordFileName,content, function(err) {
if(err) {
console.log("Failed on creating the file " + err)
}
});
fs.chmodSync(passwordFileName, '400');
}
function deletePasswordFile()
{
fs.chmodSync(passwordFileName, '777');
fs.unlink(passwordFileName,function (err) {
if (err) throw err;
console.log('successfully deleted');
});
}
and there are three statements which call these functions:
createPasswordfile(password)
someOtherFunction() //which needs the created password file
deletePasswordFile()
The problem I'm facing is when I add the deletePasswordFile() method call, I get error like this:
Failed on creating the file Error: EACCES, open 'password.txt'
successfully deleted
Since its non blocking, I guess the deletePasswordFile function deletes the file before other function make use of it.
If deletePasswordFile is commented out, things are working fine.
How should I prevent this?
writeFile is asynchronous, so it's possible the file is still being written when you try and delete it.
Try changing to writeFileSync.
fs.writeFileSync(passwordFileName, content);

How do I run a Frisby.js test inside a function

I can't figure out why this frisby tests won't run!
Basically I'm trying to import JSON from a file and check it against a return from a request. The compiler doesn't seem to find any tests when I run this file.
If anyone could possibly suggest a better way to do this? I'm thinking about trying a different way to handle the file reading. I know about readFileSync() but I do not want to use that if I don't have to! Any help would be appreciated.
function readContent(callback,url,file) {
fs.readFile(file, 'UTF8', function (err, content) {
if (err) return callback(err)
data = JSON.parse(content)
callback(null, data)
})
}
readContent(function (err, content) {
frisby.create('Testing API')
.get(url)
.expectStatus(200)
.expectBodyContains(content)
.toss()
},
url,file)
Here's one I prepared earlier:
// Read a JSON file from disk, and compare its contents with what comes back from the API.
fs.readFile(path.resolve(__dirname, 'GET_ReferenceTypes.json'), 'utf-8', function(error, data){
if (error) throw error
frisby.create('GET ReferenceTypes, inside readFile callback')
.get(URL + 'ReferenceTypes?requestPersonId=2967&id=99')
.expectStatus(200)
// JSON.parse() is required to convert the string into a proper JSON object for comparison.
// The .replace() strips the BOM character from the beginning of the unicode file.
.expectJSON(JSON.parse(data.replace(/^\uFEFF/, '')))
.toss();
});
Double check the encoding on your JSON file, because this whole thing comes apart without the .replace() call.

Call a function in node.js

I am new to node.js .Here I write a sample function in node.js to print the contents of a json file as follows.
exports.getData =function(callback) {
readJSONFile("Conf.json", function (err, json) {
if(err) { throw err; }
console.log(json);
});
console.log("Server running on the port 9090");
What I am doing here is I just want to read a json file and print the contents in console. But I do not know how to call the getData function. While running this code it only prints the sever running on the port..", not myjson` contents.
I know the above code is not correct
How can I call a function in node.js and print the json contents?
Node.js is just regular javascript. First off, it seems like you are missing a }. Since it makes the question easier to understand, I will assume that your console.log("Server... is outside exports.getData.
You would just call your function like any other:
...
console.log("Server running on the port 9090");
exports.getData();
I would note that you have a callback argument in your getData function but you are not calling it. Perhaps it is meant to be called like so:
exports.getData = function(callback) {
readJSONFile("Conf.json", function (err, json) {
if(err) { throw err; }
callback(json);
});
}
console.log("Server running on the port 9090");
exports.getData(function (json) {
console.log(json);
});
Truthfully, your getData function is a little redundant without any more content to it since it does nothing more than just wrap readJSONFile.
Don't take this the wrong way, but your code appears to be a mixed up mess of unrelated examples. I recommend you start by learning the basics of JavaScript and node.js (for example, read Eloquent JavaScript and Felix's Node.js Beginners Guide).
But on to your code. First of all, you are creating a function (called getData) and exporting it. Then you're printing "Server running on the port 9090". There is no server code in your script, and the function you created is never executed.
I think this is what you intended to write:
readJSONFile("Conf.json", function (err, json) {
if(err) { throw err; }
console.log(json);
});
Assuming that readJSONFile is a real function.

How to make javascript code to work witn node.js?

I have the following code and I know that if I use it in the terminal (node test.js, in the case the file is called test.js) but how do I make this code work in javascript with HTML? I mean, how do I make possible to click a button and execute the code? Thank you!
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyACM0", {
baudrate: 9600
}, false);
serialPort.on('error', function(err) {
console.log(err);
});
serialPort.open(function(err) {
if (err) {
console.log(err);
return;
}
console.log('open');
serialPort.on('data', function(data) {
console.log('data received: ' + data);
});
serialPort.write('1', function(err, results) {});
});
}
You can't execute this in a browser (which wouldn't let you access the serial port, for example) but there are various solutions to package some HTML code with nodejs.
The best solution today for a local all-including "desktop-type" architecture is probably node-webkit which has a good support and traction.
Another standard architecture is to simply make nodejs act as a server serving an HTML page including your button. That might be more suited for piloting an Arduino.

Categories

Resources