Multiple instances of Node Webkit (nwjs) shares cookies - node.js

I have two nwjs apps running in different nwjs executables. But cookies for both app are stored in the same folder C:\Users\Nickname\AppData\Local\node-webkit. For example, I can access cookies of the second app from the first (!!!). It's confusing.
So, one app can stole cookies from another app just using code win.cookies.get()? How to store cookies for each app separately?

You need to run your app and change the data-path, if you don't want to access the running arguments, you can use child_process, for that, the main app will create new app that store the cookies in diferent folder.
var child_process = require('child_process')
var path = require('path');
var profilePath = path.join(gui.App.dataPath,Math.random());
var child = child_process.spawn(process.execPath, ["--data-path="+profilePath,"],{detached: true});
https://github.com/nwjs/nw.js/issues/3724
I recommend you to not use cookies for save app data. You can use files (fs module).
You can also try to encrypt your data.

Related

Read files from folder before start

I want to get an array of file names from my project public/logos folder. I am using create-react-app template and as you guess, I can not use const fs = require('fs') in browser after project start.
So, is there any way to fill an array right after npm start command and getting file names array from folder or am I out of context?
const fs = require('fs')
const path = require('path')
const appRoot = require('app-root-path').path
const getNames = () => {
fs.readdir(path.join(appRoot, "public", "logos"), (err, files) => {
return files
})
}
Although the Sathishkumar is correct, it's not the only way: having an application server just for reading static images can be too much in many situations.
What you can do is to handle this by change the webpack configuration (this requires you eject first so be really careful).
From webpack you have all of the Nodejs features available but you must make those changes static for the webapp.
An idea:
manually copy with html-copy-plugin every image in the dist folder
read every image file in that folder from node and generate a list of image names
put the list of images as a global variable in your bundle by using webpack DefinePlugin
Now you will be able to read images names from this new global.
Note: this will not be a dynamic read of resources in a folder. If add/remove images you will be forced to repeat the build process of the app.
Yes. It is out of context. Not possible in browser-based JS application. You can't access the file system using Javascript in the browser.
You can use a NodeJS(or any other language for the same) to create a REST API as you mentioned which will return the files list and then can consume it(APIs like fetch or package - axios) in the frontend. This is the preferred way of doing.
If you need to read the files from file system you need to start server, like express, and then read this files on the server by request from frontend or by the link you pasted in your browser address field.

Converting Node.js command line app to web app

So this is more of an open ended question: I've started working with node and I've been creating command line applications for practice. The majority of these apps take command line arguments and make http requests to an API and serve up the results based on the arguments passed. The thing is, I would like these programs to have useful front-end interfaces so that the results are not just display via the command line terminal. Is there an easy way to accomplish this? Is this what Express is useful for?
perhaps more fully, that's what express is for and that's what routes do for you - so that your browser can be directed to a default (e.g. index.html) page or a specific page or service. If you're rendering basic html pages, stored in an /HTML folder, to the user, then you might have the following kind of code in your app:
var express = require('express');
var app = express();
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/HTML'));
followed by a series of app.get('path/from/browser') and/or app.post('path/from/broswer') statements which tell your nodejs server what to do when various get and post commands are sent to the app.
as your app gets more complex, you may want to consider the router service as a way to structure your application code and associated services.
you also need to start an http server, so the browser can actually talk to the server. You would do that in a very simple way by executing the following code:
var cfenv = require('cfenv');
var appEnv = cfenv.getAppEnv();
app.set('port', appEnv.port);
var server = app.listen(app.get('port'), function() {console.log('Listening on port %d', server.address().port);});
In this simple example, your app is now using 3 new services: express, ejs, and cfenv. You would use the standard npm install process to get this into your local app so that you can use them. From your application root folder, you would execute npm install --save express, repeating for each of the three new services.

How can I access an environment var in other modules

I use the jsonwebtoken module to Encode and Decode JWTs.
The Secret-passphrase is being saved in a config.yml file, which is being loaded in my main index.js Javascript and stored into an app Environment var app.set('jwtToken', config.jwt.token).
How can I access this environment var in another module (for example the Auth-Route Module).
Can I pass it somehow to this file?
Many thanks
I think you will need access to your app instance to access the jwtToken var in app. Alternative for you would be to pass your jwtToken as an process environment variable via
JWT_TOKEN=xyz node server.js
Now you could access it via process.env.JWT_TOKEN

Node.js, Express, Jade & Template in Package

Is it possible to store templates for an express application in a separate package?
In my usecase I'd like to have a shared package containing global templages to give all apps the same look and feel even so they run as an independent entity on another port or even another server. Local content templates could live within the app, so all I'm looking for is a way to share that kind of code between multiple apps.
Going a step further I was thinking about skinning packages which can overwrite the default templates. Once installed in the "template package" it could change the look and feel of all applications using the core templates.
Is there a way of doing that without having to drop the comfort of express?
cu
Roman
This is possible using express. You can basically mount a whole app object to a specific route (with all routes and middleware).
var express = require('express');
var coreApp = express();
var blogApp = express();
var wikiApp = express();
// init blogApp and wikiApp with middleware and routes
coreApp.use('/blog', blogApp);
coreApp.use('/wiki', wikiApp);
Now you can mount your templates into this modular apps and then mount them into your core app.
Here's a screen cast from the express creator himself, called modular web applications.

How to access localStorage in node.js?

I tried searching the web for a node module that can access the client's localStorage but wasn't able to find anything. Anyone know of one?
You can use :
node-localstorage npm module to use localStorage at the nodejs server side.
var LocalStorage = require('node-localstorage').LocalStorage,
localStorage = new LocalStorage('./scratch');
If you mean html 5 localStorage, there's no such a thing since node.js is a server-side technology. Html 5 localStorage is a client side feature supported
When the page loads, send a post that queries the contents of the client's localStorage.
Found this store
// Store current user
store.set('user', { name:'Marcus' })
// Get current user
store.get('user')
// Remove current user
store.remove('user')
// Clear all keys
store.clearAll()
// Loop over all stored values
store.each(function(value, key) {
console.log(key, '==', value)
})
LocalStorage is never accessible by the server. Ever. It would be a huge security issue.
If you need to send it to a server, then you have to have a client-side JS script which retrieves it, and then sends it to the server as part of an Ajax or POST request.
Cookies work well for when you need to pass small amounts of data regularly between server and client.
Databases on your server are best if you need to store data long-term.
For Node.js you can use HandyStorage, a fast and small npm package which behaves data like a state
Here's an example:
const HandyStorage = require('handy-storage');
const storage = new HandyStorage('./store.json');
storage.setState({
name: 'Alireza',
lastname: 'Sh',
friends: [
'Jane',
'John'
],
visited: storage.state.visited || 0
})
storage.setState({
visited: storage.state.visited + 1
})
It automatically changes the JSON file, just give it a try!
In the JS file you write this:
const LocalStorage = require('node-localstorage').LocalStorage,
localStorage = new LocalStorage('./scratch');
Also you need:
open new Terminal press Control + C (don't worry it's for clear not for copy) and type you'r file.js (for ex: server.js) and than type this: npm i node-localstorage (now you all set).
Well, I think some explanations are in handy, first of all, node JS and V8 are two different things and runs on different places. Browsers uses the v8 engine to run JS, node JS runs on servers and is v8 based, but it doesn't have everything that the browser does (like the window object). So you can't access the browser local storage from your server because it's running somewhere (browsers runs on the user machine) else, I think that you want a lib that works like local storage but in your node js serve, for that we have store -> https://www.npmjs.com/package/store.
I'm From 2022 and yet there is no way we can instantly get the browser's localStorage without using fetch or ajax to communicate to the server but if you use react or veu for instance they can access it. Because they are frontend base libraries and frameworks
We can not save to localStorage on Node.js.

Resources