Node.js reads the file but does not write JSON in the HTML - node.js

I'm currently running Node.js by Browserify for my website.
It reads the JSON file and I get the message through MQTT.
But the problem is that it seems like writefile does not work.
(Running this as node test.js in the terminal works by the way).
What is wrong with my code?
Moreover, Is this the best way to store any user data?
Thank you so much in advance.
Here's some part of my code
var fs = require("fs");
var path = require("path");
let newFile = fs.readFileSync('/home/capstone/www/html/javascript/test.json');
function testT() { //THIS WORKS FINE
let student0 = JSON.parse(newFile);
var myJSON = JSON.stringify(student0);
client.publish("send2IR", myJSON);
response.end();
};
function write2JSON() { //PROBLEM OF THIS CODE
const content = 'Some content!'
fs.writeFileSync('/home/capstone/www/html/javascript/test.json', content)
};
document.getElementById("blink").addEventListener("click", publish);
document.getElementById("write").addEventListener("click", write2JSON);

You cann't write directly for security reasons. For other hand you can use a server as API to do the filye system tasks and in the client only trigger the events.
This post is very related with your problem:
Is it possible to write data to file using only JavaScript?

Related

How to download a CSV file with selenium while bypassing the file dialog

I have been trying to access a url with a CSV file to download it in a specific directory, using the Selenium Webdriver for Firefox(geckodriver), in a NodeJS enviroment on Linux-Mint.
This is my code:
const {Builder} = require('selenium-webdriver');
const firefox = require('selenium-webdriver/firefox');
const path = require('path');
const options = new firefox.Options();
options.setPreference('browser.download.dir', path.resolve(__dirname));
options.setPreference('browser.download.folderList', 2);
options.setPreference('browser.helperApps.neverAsk.saveToDisk', 'application/x-csv');
function example(){
let driver = new Builder().forBrowser('firefox').setFirefoxOptions(options).build();
driver.get('http://insight.dev.schoolwires.com/HelpAssets/C2Assets/C2Files/C2ImportCalEventSample.csv');
}
example();
As you can see, I am correctly setting the browser option to browser.helperApps.neverAsk.saveToDisk, so as to be able to bypass the dialog. However, I am still getting the dialog no matter what I do. I haven't tried this code on Windows, but for my purposes it needs to work on Linux.
Am I missing something? Some preference that needs to be added or changed? Or does this not work on my current enviroment?
Thank you in advance for any help provided.
If you are just downloading a file from link why do you need selenium?
A much simple approach will be just to get the file by http and save to file.
const http = require('http');
const fs = require('fs');
const file = fs.createWriteStream("C2ImportCalEventSample.csv");
const request = http.get("http://insight.dev.schoolwires.com/HelpAssets/C2Assets/C2Files/C2ImportCalEventSample.csv", function(response) {
response.pipe(file);
});
If you have to use selenium let me know in the comments and i will try to find a solution for your problem using selenium.

Small api on node.js

maybe someone have example for creating small API on node.js
Example, i have function this function will return string
I need call this string from postman or inside any another project with http.
What better for create this API?
Maybe someone know good guide? I worked before with node.js only like web-server
It is best practice that building API's in nodejs with express.Here is a code in which function returns a string. You need to export it. And require the file that contains exported value in your project file with the file path. Here is my function code where I am returning a string value. func.js
var string;
function myfunc(param,callback){
var str="hello";
callback(null,str);
}
myfunc('aaa',function(err,result){
if(err){
console.log(err);
}
else{
exports.string=result;
}
});
Here is my routes file and here I am calling the string from func.js and I named this file as str.js
var http = require('http');
var express = require('express');
var main = require('./func.js');//path of file
var org = main.string;
var app = express();
app.get('/str',function(req,res){
console.log(org);
res.send(org);
});
app.listen(3000,function(){
console.log("Server listening on 3000");
});
Run the code as node str.js and in postman run the url as http://localhost:3000/str and you can see the returned string in both response and in terminal.
Hope this helps...
This tutorial shows you how to build an API in Node.js with Express.
EDIT: You can skip the database part if you don't need it.

write html content into word and download in user machine using node.js

How to use html-docx-js in node.js .
I have refered the npm site (https://www.npmjs.com/package/html-docx-js) for this. Below is the code
var converted = htmlDocx.asBlob(content);
saveAs(converted, 'test.docx');
But here is the problem, the saveAs function is missing in the tutorial.
I have downloaded filesaver.js on the client side i Iave implemented this and it works fine. But I want complete code in node.js running which it will convert my html content and will download a word file in client machine.
Looking forward for some help.
Regards,
Bikram Nayak.
var HtmlDocx = require('html-docx-js');
var fs = require('fs');
var html = 'fasfasfasdfsfsdfsf';
var docx = HtmlDocx.asBlob(html);
fs.writeFile('helloworld3.docx',docx, function (err){
if (err) return console.log(err);
console.log('done');
});

how to write a file on one controller and read the same in another controller in Node.js

I want to implement a functionality in nodejs. I have two different controllers in my node application. I has the responsibility to store the file (abc.xlsx) into local folder(mylocation) using fs module and i have done it successfully. And in my another controller i have to read the locally stored file(abc.xlsx).
Is it possible. Everytime i want to write a file from one controller and read the same from another controller. I have tried something as like the following..
exports.controller1 = function(req,res){
if(req.files.file){
fs.readFile(req.files.file.path,function(err,data){
var fileName = req.files.file.name;
getfileName(fileName);
some logic goes here......
});
}
}
function getFileName(fileName){
console.log(fileName);
}
exports.controller2 = function(req,res){
getFileName(fileName);
var filePath = fileName;
my logic goes here...
}
Need some help to get the fileName or the filePath to read a file
Thanks in advance.

Nodejs blocks and can't process next requests during ZIP file streaming

I'm trying to create a simple app which will create ZIP on the fly containg a few files and stream them to the client. Almost works. The problem what I encountered is that the nodejs blocks when streaming is in progress. All pendig requests will be processed after finishing current streaming. But what is interesting, these pending requests will be processed concurrently! So it can do this! I don't understand, why nodejs (expressjs?) can't start processing next request during streaming one file and what I did wrong... :|
I'm using node-archiver as a stream source.
Here's my part of code:
var express = require('express');
var archiver = require('archiver');
var router = express.Router();
router.get('/job/:id', function(req, res) {
var job = req.jobs[req.params.id];
var archive = archiver('zip');
archive.pipe(res);
for (var n in job.files) {
var f = job.files[n];
archive.file(job.path + f, {name: f});
}
res.setHeader("content-type", "application/zip");
res.setHeader("Content-Disposition", 'attachment; filename="reports.zip"')
archive.finalize();
});
module.exports = router;
Any advices? Thanks!
EDIT: I've noticed another problem, completely not related with archiver. I have following basic app:
var http = require('http');
var fs = require('fs');
var server = http.createServer(function (req, res) {
var stream = fs.createReadStream('file.blob');
stream.pipe(res);
});
server.listen(31922);
Tell me, why it get stuck in this case? Result is absolutely the same as using archiver. OS what I use is SmartOS (based on Open Solaris), it's Unix. Maybe this is a problem? Any ideas?
For all those of you struggling with similar problem. I'm being dumb perhaps. The solution is simple. Basically testing method was wrong. My browser (and other tested have similar behaviour) blocks processing next request from the same host name when previous one is not finished. And in this case this is not finished request as downloading is still in progress. Thanks for your help!
It seems that Archiver depends on synchronous code, there is recent issue open on github addressing this:
https://github.com/ctalkington/node-archiver/issues/85
Given that it is synchronous, that's probably where your block is comming from.
Quote:
This module depends on file-utils which in the README says: "this is a
set of synchronous utility. As so, it should never be used on a
Node.js server. This is meant for users/command line utilities."

Resources