how can I write file to windows system folder? - node.js

I want to add new fonts to my windows system folder by electron, but failed, how could I do this? here is the code which can work well in app folder.I just want to put the file in to 'c:\windows\Fonts', thank u.
var request = http.get("http://www.mysites.com/newfont.ttf", function(response) {
if (response.statusCode === 200) {
var file = fs.createWriteStream("app/font.ttf");
response.pipe(file);
}
});

In your error you can see that http is not defined, that to tell you that you probably forget to require the http module. By the way you will have to do same thing with fs module no ?

Related

Simple Server Node.js return html page

I am trying to run a local server on Node.js that returns a simple html page. The difficulty for me at this point is understanding how to make the file system handle function correctly.. I am looking for the right code to use when the /recipe extension is called in the browser.
I get the error "no such file or directory", while the path they specify is correct. There is a file in there with the correct name..
Do I have to manually add "fs" in npm?
Is there another mistake in my code?
Am I forgetting something?
I have the following code:
// strict mode catches javascript errors better..
"use strict";
// localhost port on which you can access the application in DEV
// http status codes accesses npm package that contains main API status codes
// fs is the file system handler to handle the html files
const port = 3000,
http = require("http"),
httpStatus = require("http-status-codes"),
app = http.createServer(),
fs = require("fs");
// set up route mapping for html file
const routeResponseMap = {
"/recipe": "view/recipe.html",
"/index": "<h2>this is the index page</h2>"
};
// need to open your browser localhost:port for the request to be made..
app.on("request", (request,response) => {
response.writeHead(httpStatus.OK, {"Content-Type": "text/html"});
if(routeResponseMap[request.url]){
response.end(routeResponseMap[request.url]);
if(routesResponse[request.url]){
// the error is here, file does not get read
// WHAT CODE DO I NEED HERE?
fs.readFile(routesResponse[request.url]), (error, data) => {
response.write(data);
response.end();
}
console.log("route in mapping");
}
else{
response.end("<h3>Sorry not found</h3>");
}
})
app.listen(port);
console.log("The server has started and is listening on port " + port);

How can I use the unpkg url in my nodejs project?

Is it possible to use an unpkg.com url in my nodejs project?
I have a project setup to use nodejs https to get the url and it works but I am not sure how or if its possible yet to use that in my nodejs project like we do with a regular installed npm package.
const https = require('https');
const url = 'https://unpkg.com/#tensorflow-models/speech-commands#0.3.3/dist/speech-commands.min.js';
Then I need to use it here:
async function app() {
https.get(url, (res) => {
const statusCode = res.statusCode;
if (statusCode != 200) console.error(`Error ${statusCode}: ${res.statusMessage} ${url}.`);
else console.log('Success');
});
recognizer = speechCommands.create('BROWSER_FFT');
await recognizer.ensureModelLoaded();
predictWord();
};
The response comes back with success but I ultimately need to use the package via that url. I want to be able to substitute the instance speechCommands with the res from unpkg.com. Is this possible? The reason I am trying this is because when I use the npm package I get a fetch undefined error and since this package is rather new, there isn't an issues section setup in their repo to ask.

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

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?

Issues Getting Highcharts Export Server Running Under iisnode

I am working on trying to set up the Highcharts export server under node.js using iisnode (https://github.com/tjanczuk/iisnode). It basically acts as a pipe between requests to IIS through to node. Great! Only, how do I "install" the highcharts export server so it is using iisnode? I did the instructions on how to install the highcharts-export node module but it is installed under (Windows) AppData\Roaming\npm. How to move or point iisnode to the export server?
This export server is run via the following once installed from npm:
highcharts-export-server --enableServer 1
So, to get this installed and used in IIS8 + iisnode
1) What is the right directory to install export server locally (on Windows the modules pulled in via npm go to C:\Users\\AppData\Roaming\nmp\ where is the logged in user using npm to install the package)?
2) What is the iisnode configuration necessary for this?
I have the iisnode setup and running on our development box and all the examples work. My confusion lies partly with the utter lack of documentation for issnode. All the links I have found just repeat the items listed in the links from the issnode developer with no actual "here is how you take a node app that exists in npm and have it work in issnode." I don't necessarily need my hand held every step of the way. I am just seeing no list of steps to even follow.
install node (if not already installed)
install iisnode (if not already installed => https://github.com/tjanczuk/iisnode)
verify IIS has iisnode registered as a module
create a new Application Pool, set to "No Managed Code"
create a new empty web site
load the iisnode sample content into it, update the web.config
verify you can hit it and it runs and can write it's logs
go to the IIS web site folder and run these npm commands
npm init /empty
npm install --save highcharts-export-server
npm install --save tmp
add file hcexport.js and reconfigure web.config
var fs = require('fs');
var http = require('http');
var path = require("path");
var tmp = require('tmp');
const exporter = require('highcharts-export-server');
http.createServer(function (req, res) {
try {
if (req.method !== 'POST') { throw "POST Only"; }
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
if (body === '') { throw "Empty body"; }
var tempFile = tmp.fileSync({discardDescriptor: true, postfix: ".svg", dir: process.cwd()});
var input = JSON.parse(body);
input.outfile = path.basename(tempFile.name);
exporter.initPool();
exporter.export(input, function (err, exres) {
if (err) { throw "Export failed"; }
var filename = path.join(process.cwd(), exres.filename);
exporter.killPool();
fs.readFile(filename, function(err, file) {
res.writeHead(200, { 'Content-Type': 'image/svg+xml', 'Content-disposition': 'attachment; filename=' + exres.filename });
res.write(file.toString());
res.end();
tempFile.removeCallback();
});
});
});
} catch (err) {
console.log({port: process.env.PORT, error: err});
res.writeHead(409, { 'Content-Type': 'text/html' });
res.end(err.message);
}
}).listen(process.env.PORT);
Extend as needed to support the export types you plan to use.
The highcharts-export-server uses phantomjs internally and this can run away under some error conditions using up 100% of available CPU, if you see this you can kill it using:
Taskkill /IM phantomjs.exe /F
The solution from saukender seems to work, however it seems that it always initializes a new pool of phantom workers every time.
If you already have node and issnode setup, another solution is to directly start the highcharts export server and not call the export function manually. This seems to provide a better performance, since it doesn't initialze the worker pool on every request.
// app.js
const highcharts = require("highcharts-export-server");
highcharts.initPool();
highcharts.startServer(process.env.PORT || 8012);
Don't forget to point your web.config to app.js.
I found these two resource quite useful during setup:
https://www.galaco.me/node-js-on-windows-server-2012/
https://tomasz.janczuk.org/2011/08/hosting-nodejs-applications-in-iis-on.html

How to create project in node.js using html5 and mysql?

I want to include my another js file and one html file(dashboard.html).How it will possible?
var file = require('display.js'),
var http = require('http'),
fs = require('fs');
fs.readFile('./dashboard.html',file, function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(9236);
});
Please suggest me proper way to do this thing?
In nodejs if you want to add your own libraries/js.
use this
var file = require('./display.js'), // or the path to file it will load file from path
instead of
var file = require('display.js'), // here it will search in node_modules filder
You should know how node look for modules. I'm adding what I know.
If you will require some ./somefolder/somefile.js it will search for the path ./somefolder/somefile.js and load that file.
If you will add 'somefile.js it will search for the librery somefile.js to node_modules folder in your root directory. If it won't get the file there it will go to global path of node_modules.
If it didn't get that file in global node_modules also, it throws an error
Cannot find module <file.js>
Anyone can improve my answer if anything I missed.

Resources