Same config for node.js and for browser javascript - javascript

Is it possible to have the same config file for server node.js and client js code?
Now I use .json config for node.js, but can convert it to any format

Without more information, all I can offer is a simple suggestion: Require.js. You can reference a config module in the Node.js code and reference it in the client script. Just make sure that the config file can be served to the client.
// Example reference
var config = require('./data/config.js');

Related

Using javascript interpreter 'otto', How to read a file in client side

I'm having difficulties.
I am implementing logic to read the file, encodes it, and send it to the server.
Currently, the library used as javascript interpreter is using 'otto'.
I imported 'fs'(I know it is Built-in module) like
var fs = require("fs");
fs.readFileSync('./test.txt', 'utf8');
but occurred error Module not found: Error: Can't resolve 'fs'
So I inserted node: { fs: "empty" } in webpack.config.js file.
Then compile error is not occurred. But when I called a function that contains fs.readFileSync using cli, occurred error.
TypeError: 'readFileSync' is not a function
First question:
I know that 'otto' is just javascript interpreter. For this reason, when I imported 'fs', is there a failure to find the module?
Second question:
If not, How can I read a file from the clientside and send it to the server?
Last question: Using 'otto', It is impossible??
This is my spec.
macOS High Sierra, Webpack 4.9.1, Node.js 8.11.1.
How to read a file in client side
Since you mention Webpack, I'm assuming the "client side" here is a browser. To read a file from a browser, you use the File API. Note that your code cannot specify what file to read; the user does that, either by picking a file in an input type="file" element, or dragging a file into a drop area. In both cases, you'll get a File object, which you can read using the File API.
You cannot use the fs Node.js module in a browser.

Conditional javascript source code

Background:
I have 3 different URLs, one per environment (dev, test, prod), and I don't want to expose all the URLs in the client (source code).
How can I expose in the client code, just the one corresponding to the environment in context?
Note: As I understand, I need to do something in the build process using environment variables (I'm using node.js). However, I don't want to touch anything related with webpack, as what I'm trying to do is a standalone package that can be imported in any application regardless of the framework they are using. Webpack plugins/configuration are not an option, but I can use any npm package if required.
During your build process, you can check the environment variable and then copy over a config file. For example, you could keep your URIs in /config/<env>.js, and then copy/rename it to /settings.js during the build. Your URL could be exported from that.
The following npm package fits my requirements completely https://www.npmjs.com/package/config , you can load conditional files based on the node environment variable NODE_ENV, so when NODE_ENV=development, the file /config/development.js is used to create the build. you can use different extensions for the config files, also you can customize the config folder path by changing the environment variable $NODE_CONFIG_DIR heres an example:
const config = require('config');
process.env.$NODE_CONFIG_DIR = './' // relative path ./config
const url = config.get('url');
//if NODE_ENV is development will load the file config/development.js
console.log(url);

readFileSync is not a function

I am relatively new to Node.js and have been looking around but cannot find a solution. I did check the require javascript file and it does not seem to have a method for "readFileSync". Perhaps I don't have a proper require file? I had a hard time finding this file, everywhere talked about it but most people did not post where to get it.
I installed Node.js and have the require.js file. My current code is like this:
fs = require(['require'], function (foo) {
//foo is now loaded.
});
console.log("\n *STARTING* \n");
// Get content from file
var contents = fs.readFileSync("sliderImages", 'utf8');
I had a bit at first getting require to work however it seems to load the require JavaScript file. I have been following guides and I am not sure why I get this error:
Uncaught TypeError: fs.readFileSync is not a function
I have tried many fixes and cannot seem to figure this one out.
Node.js does not use Require.js. Require.js was built so that you could have asynchronous module loading on the client-side (in your browser).
Node.js uses CommonJS style modules. Your code using CommonJS would look like this:
var fs = require('fs');
console.log("\n *STARTING* \n");
var contents = fs.readFileSync("sliderImages", "utf8");
If we assume you saved this in a file called main.js you would then enter this command in your console (make sure you are in the same directory as the file):
node main.js
This code will not run in the browser. Node.js runs on the server. If you want to load a JSON file on the browser side then you'll need to load it using AJAX. There are numerous resources available to show you how to do this. Be aware that you must either run your page from a server or have a special flag enabled to load in files from the file system.
This error can arise if you write
const fs = import('fs');
in a Node module
but should write
import fs from 'fs';

Using a third party library in a node application

In my server.js I have the following functions:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
I have to use this library as well but I cannot figure out how to use this?
The documentation say that I can just do npm install node-uuid and var uuid = require('node-uuid');
I tried to add var uuid = require('node-uuid'); to server.js but I cannot use uuid in any controller js file like var id = uuid.v1();. I get Error: Can't find variable: uuid.
The controller file looks like this:
(function() {
angular
.module("WebApp")
.controller("TestController", TestController);
function TestController($location) {
// need to get a uuid here
}
})();
How should I use this library?
If your code above client-side code and you really trying to achieve that on client side with angular framework you can try AngularJS wrapper for the original node-uuid library i.e angular-uuid.
Create angular-uuid.js file in your js folder of client
use this link to copy the contents for this file
https://github.com/munkychop/angular-uuid/blob/master/angular-uuid.js
and save this file with the copied contents.
use a regular script tag to include this lib
<script src="angular-uuid.js"></script>
Include angular-uuid in your module defination and inject that in your controller
(function() {
angular
.module("WebApp",["angular-uuid"])
.controller("TestController", ["uuid",TestController]);
function TestController(uuid) {
// need to get a uuid here
}
})();
npm install won't do you any good in your client-side angular code since it has no access to the node_modules.
In the page you linked above, the instructions say to include it in your html with something like:
<script src="uuid.js"></script>
If you do that, then if your controller code runs after the script noted above has been loaded, then you should be good to go.
If your code above isn't client-side code, then I'm not sure what you're doing with angular on the server side.
NOTE: If you're using bundling with something like web-pack then you could use npm to install the uuid library. Please let us know if you're doing that.
You can still use node modules in the frontend if you use a bundler like webpack or browserify. In that case you can do:
var uuid = require('uuid');
Just like you can on the backend. Make sure you link the files bundled by the bundler you chose, and this should work.
Keep in mind that there's a (slight) performance difference between loading it in a script tag (more http requests) vs using a bundler (larger file size).

Share constant from node.js sever to js files in frontend app

I have a node.js server and a package.json file. In that file I set some variables. For exemple "version" : 3.0. I can access those variables very easily in the node.js server. (Is there a way to get version from package.json in nodejs code?)
var pjson = require('./package.json');
console.log(pjson.version);`
But how can I pass it to my js app working on the frontend? Can I create a constant.js file that is created went I start the server (only ones).
I do not want to pass the variable as an argument every time I render a page.
I use the ejs to render my pages.
Thank you for your help.
You could set a cookie in the initial response.
response.setHeader("Set-Cookie", ["version=3.0"])

Categories

Resources