Get local json file using request-promise - javascript

I'm making a node/express app and am querying a test json file using npm request-promise. Node is spitting out the following error in my <title> tags:
Error: <title>Invalid URI "../testJSON/user.json"</title>
I believe my pathing is correct, so am unsure why it's an invalid URI.
I've also provided the entire project path URI with the same issue:
return rp('http://localhost:3000/app/testJSON/user.json');
User Service:
module.exports = {
getUserData: function(){
var options = {
uri : '../testJSON/user.json',
method : 'GET'
}
return rp(options);
}
}
User Controller:
var User = require('../services/User.service');
User.getUserData()
.then(function(data){
res.render('pages/userdata', {
title: 'User Data',
content: JSON.parse(data)
});
})
.catch(function(err){
console.log(err);
});
Pathing:
User Service: projectroot/app/services/userService.js
User json file: projectroot/app/testJSON/user.json
Update: trying with node fs to fetch local file
fs = require('fs');
module.exports.index = function (req, res) {
fs.readFile('../testJSON/user.json', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
res.render('pages/user', {
title: 'User',
content: JSON.parse(data)
});
});
...
Node error:
{ [Error: ENOENT, open '../testJSON/user.json'] errno: -2, code:
'ENOENT', path: '../testJSON/user.json' }

Relative paths (starting with ../ or ./) are relative to the current working directory. If you want to read a file relative to the current JS source file, you need to prefix the path with __dirname, which is the directory where the current JS source file resides:
fs.readFile(__dirname + '/../testJSON/user.json', ...);
Or the more elaborate (but probably more correct) way:
var path = require('path);
...
fs.readFile(path.join(__dirname, '../testJSON/user.json'), ...);

Related

AJAX: Listing out the content of a directory. Unable to resolve URL

I'm trying to display some images contained in a folder, inside a div. I'm using AJAX to do that in a JavaScript file called edit that is one directory away from the index route. I'm using Node.js. The code I have written is as follows.
var folder = "../images/emojies/";
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
// some code
});
}
});
I get this error:
"GET /images/emojies/ 404"
The weird thing is that when I go to this for example:
"/images/emojies/image.png", It finds the directory with no errors!
It's like it can't find folders but it can find files?
routing code if needed:
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'xx' });
});
/* GET edit page. */
router.get('/edit', function(req, res, next) {
res.render('edit', { title: 'xx' });
});
You could have done something like follows.
var app = require('express')();
var http = require('http').Server(app);
var fs = require('fs');
var clients = 0;
app.get('/images/emojies', function(req, res) {
var path = "public/images/emojies/"; //Could be obtained from req.path however, needs to resolve the path properly.
fs.readdir(path, function(err, items) {
res.send(items); // items is an array
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
/images/emojies would be the endpoint that you would contact and you could use your existing AJAX request as follows.
var folder = "/images/emojies";
$.ajax({
url : folder,
success: function (data) {
//Under data, you have a stringified array of the file names.
}
});
The best thing about this method is that it gives you more fine-grained control over the file types and file names that you are going to expose, especially given that you are going to expose a part of your file system.
You can use path module to fix your problem:
https://nodejs.org/api/path.html
I think that it should look like this:
var folder = path.normalize("../images/emojies/");
In Nodejs when you access to folder you have to write folder root with ./ sign.
For example
var folder = "./../images/emojies/";//Firstly you have to write "./" it access to the same folder where your file is then go up another folder
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
// some code
});
}
});

How to get files list using fileSystem?

I am trying to get list of files in specified directory but its throwing error any idea what is implemented wrong in below code.
service.js
var fs = require('fs');
var path = require('path');
var async = require('async');
var filePath = path.resolve('./logs/dit/');
function checkSearchObj () {
fs.readdir(filePath,function (err, files) {
files.forEach(function(file) {
console.log(file);
});
})
}
checkSearchObj();
error
TypeError: Cannot read property 'forEach' of undefined
at C:\Users\sh529u\WebstormProjects\ulog\app\serverf
s:8:15
at FSReqWrap.oncomplete (fs.js:82:15)
Change this:
function checkSearchObj () {
fs.readdir(filePath,function (err, files) {
files.forEach(function(file) {
console.log(file);
});
})
}
to this:
function checkSearchObj () {
fs.readdir(filePath,function (err, files) {
if (err) {
console.log('Error:', err);
return;
}
files.forEach(function(file) {
console.log(file);
});
})
}
to see what's the error.
You need to check for errors instead of assuming that there was no error or otherwise you will try to access undefined variables and the only error you'll see is that you access undefined and not the actual error that's in err in this case.
Your callback will either get the err or the files but not both.
Update:
After changing the code to display error you got:
Error: { [Error: ENOENT: no such file or directory, scandir 'C:\Users\Web stormProjects\ulog\app\serverfiles\logs\dit'] errno: -4058, code: 'ENOENT', syscall: 'scandir', path: 'C:\\Users\\sh529u\\WebstormProjects\\ulog\\app\\serverfiles‌​\\logs\\dit'
Which means that the program doesn't display the files in the directory because there is no such directory. Mystery solved. Now you can see how useful it is to actually check the errors.

fs.readFileSync Error

I am trying to use the html-pdf node module to generate pdfs from html. I am currently running this using the cloud9 IDE.
My code is:
var fs = require("fs");
var pdf = require('html-pdf');
var html = fs.readFileSync('./test.html', {encoding: 'utf8'});
var options = { format: 'Letter' };
app.post('/pdf',function(req, res) {
pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/app/businesscard.pdf' }
});
});
I get the following Error:
[Error: Fontconfig warning: ignoring C.UTF-8: not a valid language tag]
Does anyone know how i can resolve this issue?
This is due to a bug in fontconfig. You can see here
Open your terminal and execute locale -a you will see list of fonts. Then select it like LC_ALL=C
may it can help

Copy a source file to another destination in Nodejs

I'm trying to copy an image from a folder to another using fs-extra module .
var fse = require('fs-extra');
function copyimage() {
fse.copy('mainisp.jpg', './test', function (err) {
if (err)
return console.error(err)
});
}
This is my directory
and this is the error I get all the time:
Error {errno: -4058, code: "ENOENT", syscall: "lstat", path:
"E:\mainisp.jpg", message: "ENOENT: no such file or directory, lstat
'E:\mainisp.jpg'"}
and by changing destination to ./test/ I get this error
Error {errno: -4058, code: "ENOENT", syscall: "lstat", path:
"E:\Development\Node apps\Node softwares\Digital_library\mainisp.jpg",
message: "ENOENT: no such file or directory, lstat 'E:\Devel…
apps\Node softwares\Digital_library\mainisp.jpg'"}
Note: I'm not testing this in browser. It's an Nwjs app and the pics of error attached are from Nwjs console.
You can do this using the native fs module easily using streams.
const fs = require('fs');
const path = require('path');
let filename = 'mainisp.jpg';
let src = path.join(__dirname, filename);
let destDir = path.join(__dirname, 'test');
fs.access(destDir, (err) => {
if(err)
fs.mkdirSync(destDir);
copyFile(src, path.join(destDir, filename));
});
function copyFile(src, dest) {
let readStream = fs.createReadStream(src);
readStream.once('error', (err) => {
console.log(err);
});
readStream.once('end', () => {
console.log('done copying');
});
readStream.pipe(fs.createWriteStream(dest));
}
Try:
var fs = require('fs-extra');
fs.copySync(path.resolve(__dirname,'./mainisp.jpg'), './test/mainisp.jpg');
As you can see in the error message, you're trying to read the file from E:\mainisp.jpg instead of the current directory.
You also need to specify the target path with the file, not only the destination folder.
Try:
const fs = require('fs');
fs.copyFileSync(src, dest);

Cannot GET /the route Error

I'm following this tutorial (source code) and added the highlighted code.
// app.js
app.get("/notebooks", function(req, res) {
var client = new Evernote.Client({ token: req.session.oauthAccessToken }),
noteStore = client.getNoteStore();
noteStore.listNotebooks(function(err, noteBooks) {
res.send(err || noteBooks);
});
});
app.get('/importNotes', function (req, res) {
res.send('importNotes');
});
app.get("/notes/:guid", function(req, res) {
var client = new Evernote.Client({ token: req.session.oauthAccessToken }),
noteStore = client.getNoteStore();
noteStore.getNote(req.params.guid, true, true, true, true, function(err, note) {
if (!err) {
note.content = ENML.HTMLOfENML(note.content, note.resources);
}
res.send(err || note);
});
});
another attempt:
app.get('/importNotes', function (req, res) {
res.render('importNotes', {});
});
I created importNotes.html near to index.html.
After starting the server with node app.js
I'm getting an error stating Cannot GET /importNotes
when I access localhost:3000/importNotes
I plan to use this page to add additional features after I deal with this issue (import the notes from the special txt file).
What I'm doing wrong and how I can correct it?
How to define correctly the needed routes ?
This is Steve - thanks for trying out the code !
If you use this code :
app.get('/importNotes', function (req, res) {
res.send('importNotes');
});
Then I would expect the server will send back to the browser the string "importNotes". Perhaps if you have a file called "importNotes" there is some confusion.
If you want to create a file called importNotes.html - then just put it into the "public" folder. It will then be accessible via localhost:3000/importNotes.html
The line :
app.use(express.static(__dirname + "/public"));
Tells Express to serve the contents of the "public" folder at the root level of your application, so any files you put in that folder should be GETable. e.g.
/public
index.html
steve.html
localhost:3000/steve.html

Categories