I am developing a web app with Angular 2, typescript, nodejs and Visual Studio. I want to read a file located in my wwwroot folder. so far I have created the following class:
///<reference path="../../node_modules/angular2/ts/typings/node/node.d.ts"/>
export class LoadConfigurationService {
fs: any;
constructor() {
this.fs = require('fs');
let data = this.fs.readFileSync('input.txt');
}
}
The problem is that I always get the error "readFileSync is not a function". I have tried to install the node file system module by adding the following line
"file-system": "^2.2.1"
to my package.json dependencies. I've also added
"node.TypeScript.DefinitelyTyped": "2.8.8"
to my project.json dependencies. But it keeps giving me the same error. What am I doing wrong?
Your code works for me, such as it is. What error are you getting? Here's the (slightly amended) ts:
declare var require: any;
export class LoadConfigurationService {
fs: any;
public data: string;
constructor() {
this.fs = require('fs');
this.data = this.fs.readFileSync('input.txt').toString();
}
}
const obj = new LoadConfigurationService();
console.log(obj.data);
Run this through tsc v1.8.7 produces:
"use strict";
var LoadConfigurationService = (function () {
function LoadConfigurationService() {
this.fs = require('fs');
this.data = this.fs.readFileSync('input.txt').toString();
}
return LoadConfigurationService;
}());
exports.LoadConfigurationService = LoadConfigurationService;
var obj = new LoadConfigurationService();
console.log(obj.data);
Run this with a suitable input.txt (consisting of "File Contents", for me) in the local directory and get:
$ node temp.js
File Contents
Possible problems
There are a couple issues I can see that might get in your way.
The code depends on the native node fs, not "file-system": "^2.2.1"
The worth of the referenced npmjs library aside, you are invoking the native fs library.
Don't require a dependency inside a constructor.
Dependencies for objects is a problem and worth reading about, but this is not a good way to handle it. fs should be immutable, so there's no advantage to requiring it each time the object is constructed. Just one line at the top of the file will do:
const fs = require('fs');
fs inside Angular?
I'm not sure what the snippet has to do with Angular, but if this code is getting webpacked or browserified things will become difficult. fs is for file system access and bundling that into the browser will not end well.
Related
I use var child = require("child_process").execFile; to run an external .exe file. When i run the app in debug mode everything runs smoothly. When i build and pack the application then it throws the following error.
Uncaught TypeError: (0 , a(...).execFile) is not a function
My code:
var path = require("path");
export function silentPrintPDF(htmlString) {
var child = require("child_process").execFile;
var executablePath = path.join(
__dirname,
"extraResources",
"ElectronPrinter.exe"
);
var parameters = [htmlString];
child(executablePath, parameters, function(err, data) {
console.log(err);
console.log(data.toString());
});
}
I pack the app with the following command:
"electron:pack": "yarn build && electron-builder build -w"
From my comment, the answer ended up being to use window.require to prevent it getting confused between Electoron's require and Browserify's require.
Source
I want a Config File (JSON) in root folder after build to config my app.
like Translation and API Urls and ...
Can I do this with create react app?
Create config.js or json file outside src directory and include it in index.html like
<script src="%PUBLIC_URL%/config.js" type="text/javascript"></script>
configure parameters in config.js
config.js
var BASE_URL = "http://YOUR-URL";
you can get paramenters like
const BASE_URL = window.BASE_URL;
You can store you JSON file in the public/ folder and it'll automatically provide this file when you host your Create React App.
Something like: /public/my-configuration-file.json
then when you restart your application:
localhost:3000/my-configuration-file.json
will provide you this json file.
You could create a custom hook that reads a "public" config file using fetch.
// This path is relative to root, e.g. http://localhost/config.json
const configFile = './config.json'
export function useConfig() {
const [config, setConfig] = useState(initialConfig);
useEffect(() => {
(async function fetchConfig() {
try {
const response = await (await fetch(configFile)).json();
setConfig(response);
} catch (e) {
console.log(e);
}
}());
}, []);
return config;
}
Then use it anywhere in you app
function App() {
const config = useConfig();
return (
<div>{config.foo}</div>
);
}
You'll always have an up to date non-cached version of it's data.
updating this topic with a brand new package that is available now that brings the joys of .Net Configuration to the JavaScript world: wj-config.
This package is pretty much an exact answer to what you need. Read this blog post for more information.
It is incredible to me how during over 6 years nobody filled in this gap in React (and JavaScript in general). Anyway, give wj-config a try. I think it will be a positive experience.
Below is my dispatcher code
var Dispatcher = require("flux").Dispatcher;
var assign = require("react/lib/Object.assign");
var AppDispatcher = assign(new Dispatcher(), {
handleViewAction: function(action){
console.log('action', action)
this.dispatch({
source: 'VIEW_ACTION',
action: action
})
}
});
module.exports = AppDispatcher;
gulp is not starting it is throwing error
Error: Cannot find module 'react/lib/Object.assign' from '/Users/shanky-munjal/projects/testFlux/src/js/dispatchers'
at /Users/shanky-munjal/projects/testFlux/node_modules/browserify/node_modules/resolve/lib/async.js:46:17
at process (/Users/shanky-munjal/projects/testFlux/node_modules/browserify/node_modules/resolve/lib/async.js:173:43)
at ondir (/Users/shanky-munjal/projects/testFlux/node_modules/browserify/node_modules/resolve/lib/async.js:188:17)
at load (/Users/shanky-munjal/projects/testFlux/node_modules/browserify/node_modules/resolve/lib/async.js:69:43)
at onex (/Users/shanky-munjal/projects/testFlux/node_modules/browserify/node_modules/resolve/lib/async.js:92:31)
at /Users/shankymunjal/projects/testFlux/node_modules/browserify/node_modules/resolve/lib/async.js:22:47
at FSReqWrap.oncomplete (fs.js:82:15)
I am using react 15.2.1
use Object.assign
A long time ago Dan Abramov wrote:
This is a gentle reminder that require('react/lib/SomeInternalModule')
in your component will break in some release regardless of semver.
npm install object-assign --save
this code will work
var assign = require("react/lib/Object.assign");
this code instead of
var assign = require("Object-assign");
I have
import fs from 'fs'
and in my package.json I have
Then I run the command
> npm i fs
> fs#0.0.2 node_modules/fs
next in my React store I import 'fs' module
import fs from 'fs'
However when I try to use fs
I don't see methods except for constructor and a few other __methods. I don't see the method createReadStream or any other file manipulation methods.
Does anybody know what is wrong? (using Webpack) and can give more information upon request, but I am getting this far...
ps: why is it that I can npm i fs --save when I read on other posts that I do not have to do that (using node 5.5.0)
import Reflux from 'reflux'
import AddItemActions from '../actions/AddItemActions'
import request from 'superagent-bluebird-promise'
import fs from 'fs'
var ImageStore = Reflux.createStore({
init(){
.
.
.
},
decryptImage(file) {
var reader = new FileReader();
var info = {}
reader.onload = (output) => {
debugger
request.post("https://camfind.p.mashape.com/image_requests")
.set("X-Mashape-Key", "KEY")
.set("Content-Type", "application/x-www-form-urlencoded")
.set("Accept", "application/json")
.send({'focus': { 'x': 480}})
.send({'focus': { 'y': 640}})
.send({'image_request': {'altitude': 27.912109375}})
.send({'image_request': {'language': "en"}})
.send({'image_request': {'latitude': 35.8714220766008}})
.send({'image_request': {'locale' : "en_US"}})
.send({'image_request': {'longitude': 14.3583203002251}})
.send({'image_request': {'image': fs.createReadStream("/path" + 'file.jpg')}})
.then(function (result) {
console.log(result.status, result.headers, result.body);
this.info = result
},
function(error) {
console.log(error);
})
}
reader.readAsDataURL(file);
return info
},
.
.
.
.
})
In create-react-app they have stubbed out 'fs'. You cannot import it.
They did this because fs is a node core module.
You'll have to find another solution to that problem. See this ticket.
It's possible this might be an environment issue. It's not possible for the browser to interpret and run some Node server-side modules like fs.
The solution is to run the fs methods in a Node environment (server-side) or to find a package which offers the same functionality but written for the browser.
It's discussed in this question...
Module not found: Error: Cannot resolve module 'fs'
And this question...
Use fs module in React.js,node.js, webpack, babel,express
npm i babel-plugin-preval
Though browser does not allow accessing file system during runtime, You can use prevail in React to read content from file system into memory during build time
like so
// loading content of text file into react project during build time.
// which means everytime text content is changed, you need to rebuild the project to get the updated content.
const greetingContent = preval`
const fs = require('fs')
module.exports = fs.readFileSync(require.resolve('./greeting.txt'), 'utf8')
`
console.log(greetingContent);
It's the same question as here, but I don't understand the answer. So, my question is about the answer.
The answer is
Your react.js file/module isn't exposing the variables React and
ReactDOM you instantiate. In node, you make these methods public by
modifying the module.exports object like so:
module.exports = { React: React, ReactDOM: ReactDOM }
Finally, my question is: Where do "you make these methods public"?
You are making these methods public by defining them on the module.exports property. For instance, say you have a file reactExports.js with
var iWontGetThere = 'I am in this module only';
module.exports = { React: React, ReactDOM: ReactDOM }
now in another file, you can require these methods and use them, like so:
var React = require('reactExports').React;
var SweetComponent = React.createClass({
render: function() {
return (
<div>React is cool and I can use it in here!</div>
);
}
});
module.exports = SweetComponent;
Now imagine you want to render SweetComponent in another component. If I hadn't written module.exports = SweetComponent, requiring this module in another component would have no effect as all as you would be importing an empty object {}.
Let's say I tried to console.log(React.iWontGetThere); What would happen? I would get a reference error, as it was not exported with the contents of reactExports.js-it only exists in that module, but it is not exposed.
This is a contrived example, but the interesting story here is the ability to bring in encapsulated modules. I suggest reading more about node modules here
and checking out this answer as well.
and making some examples to get the hang of it.
tl;dr: defining variables and not having a module.exports = some_value statement then requiring that same file will default to an empty object.