Node.js file not found - html

I'm using Node.exe in the following file structure
Node/
node.exe
index.js
/view
index.html
When running the following code:
var html;
fs.readFileSync('/view/index.html', function(err, data) {
if(err){
throw err;
}
html = data;
});
I get the following error:
Error: ENOENT, The system cannot find the file specified. '/view/index.html'
Can you see what's causing the error? I'm quite new to node.js.
Additional information:
I'm running Windows 7 64 bit, up to date version of node.exe.
I've found the solution!
When node.exe is run through cmd the default directory for node.exe is user.... that's where I was going wrong, it wa using a different directory to where the node.exe is located.

Few things:
You should resolved the relative path first to real path and try reading the file.
Read the file asynchronously to get the callback
Relative path should be corrected. The "./view/index.html" in my code is the path relative to where you start your node.js engine.
Rough code will be:
// get real path from relative path
fs.realpath('./view/index.html', function(err, resolvedPath) {
// pass the resolved path to read asynchronously
fs.readFile(resolvedPath, function(err, data) {
// assign the variable per your use case
html = data;
})
});
Note that I am using version 4.11 (latest stable version)

You might wanna lose the Sync part. Only readFile when you have a callback.
Also: ./path, not /path.

Related

Redirect in express

I am using express and I would like to redirect to another file since my server is not always up and running. I can not understand why I am receiving a HTML document when my file is JSON. It looks like it gets redirected, but the result is wrong. I can see that my page is redirected from the old URL to the new URL. So it looks like that part is working. But I am not receiving my local json-file in the response.
What I have in my server index.js file:
app.use('/my/original/url', (req, res) => {
res.writeHead(302, { location: '/mock/mockedresult.json' });
res.end();
});
I found out that I need to make my mock folder available. I did so by adding this line of code above the code snippet in my question:
app.use('/mock', express.static(resolve(process.cwd(), 'server/mock')));

Not Writing To JSON file. fs.writeFile not working

I have this fs.writeFile code that is suppose to update the localdata.json file when a newWorkout is POST'ed to the database, this takes local state data in an attempt to write to the file..
it wont work though and throws a , TypeError: fs.writeFile is not a function error.. working on the fix now but if anyone sees anything help is appreciated.
fs.writeFile(
"./localdata.json",
JSON.stringify(newWorkout.eventDateTime),
"utf-8",
function(err) {
if (err) throw err
console.log("Done!")
}
)
Given that you are working in a Node.js environment, is seems like fs is not a proper Node.js File System object. Copied from the Node.js 10.x documentation:
To use this module:
const fs = require('fs');
Nodes File System cannot be used "browser side" these calls are meant to happen on the server side of things.
Did you include:
var fs = require("fs");
...the rest of your code...

Trouble with getting script to recognize a JSON file in the directory (Google API)

So I am attempting to learn how to use the Google Sheets API with Node.js. In order to get an understanding, I followed along with the node.js quick start guide supplied by Google. I attempted to run it, nearly line for line a copy of the guide, just without documentation. I wind up encountering this: cmd console output that definitely didn't work.
Just in case anyone wants to see if I am not matching the guide, which is entirely possible since I am fairly new to this, here is a link to the Google page and my code.
https://developers.google.com/sheets/api/quickstart/nodejs
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
}
authorize(JSON.parse(content), listMajors);
});
I have tried placing the JSON file in each and every part of the directory, but it still won't see it. I've been pulling hairs all day, and a poke in the right direction would be immensely appreciated.
From your command output:
Error loading client secret file
So your if (err) line is being triggered. But since you don't throw the error, the script continues anyway (which is dangerous in general).
SyntaxError: Unexpected token u in JSON at position 0
This means that the data you are passing to JSON.parse() is undefined. It is not a valid JSON string.
You could use load-json-file (or the thing it uses, parse-json) to get more helpful error messages. But it's caused by the fact that your content variable has nothing since the client_secret.json you tried to read could not be found.
As for why the file could not be found, there could be a typo in either the script or the filename you saved the JSON in. Or it may have to do with the current working directory. You may want to use something like this to ensure you end up with the same path regardless of the current working directory.
path.join(__dirname, 'client_secret.json')
Resources
path.join()
__dirname

Node settings file vs mysql store

i've build my first Node app in which i need to use 5-10 global variables a lot. The thing is i would like to be able to change those values without restarting the server.
So what i though was setup an interval and update those files either from a ( JSON ? ) file or through a couple of queries to the database.
Now what would be my better option here ? Both mysql and read file modules are used in the app.
Security based wouldn't it be best to place the json file behind the public folder and read from that ? Although without sql injection being possible i think in the DB should be pretty safe too.
What do you guys think ?? Still a newbie in Node JS.
Thanks
With yamljs, the overhead is that you will need to install it. From your question, it seems you are already using a bunch of 3rd party modules in your app.
Why not use something that is a part of node.js itself?
Use the fs module.
Example:
var fs = require('fs');
var obj;
fs.readFile('myData.json', 'utf8', function (err, data) {
if (err) throw err;
obj = JSON.parse(data);
});
Docs: https://nodejs.org/api/fs.html#fs_fs_readfile_file_options_callback
A common technique for passing configuration variables to a server is via a YAML file. Normally this file is read once when the server starts but you could periodically query they file to see when it was last updated and if the file was changed update the configuration variables currently in use.
yamljs
YAML = require('yamljs');
config = YAML.load('myfile.yml');
then you can periodically check the last time a file was modified using the mtime property of fs.stat
fs.stat(path, [callback])
If you find that the last modified time has changed then you can re-read the YAML file and update your config with the new values. ( you will probably want to do a sanity check to make sure the file wasn't corrupted etc. )
If you don't want to write the file watching logic yourself I recommend checking out chokidar
// Initialize watcher.
var watcher = chokidar.watch('myfile.yml', {
ignored: /[\/\\]\./,
persistent: true
});
// Add event listeners.
watcher.on('change', function(path) {
// Update config
})

Removing case sensitivity Node subfolder

I have a Linux webserver using node which hosts a directory containing a static index.html file. I am wondering how I can make it so a user getting to the correct URL does not rely upon case sensitivity.
Currently, server.com/caa/ points to something different than server.com/CAA/ -- the directory holding index.html is lowercase "caa"
Have you tried adding some middleware that coverts all urls to lower case? Heres an example of one way of doing this
app.use(function(req, res, next) {
req.url = req.url.toLowerCase();
next()
});