I tried to parse json file in node
but there always error
and I google it but cannot solve it .
Can you help me?
undefined:1
undefined
^
SyntaxError: Unexpected token u
at Object.parse (native)
at Object.<anonymous> (app.js:13:19)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
this's my code
var app = express();
var mongodb = require("mongoskin");
var fs = require('fs');
var content;
fs.readFile('./config/db.json', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
var config = JSON.parse(content);
app.get('/', function(req, res){
res.send(config.left);
});
app.listen(process.env.VCAP_APP_PORT || 3000);
and the db.json is this. As you can see, there are no errors.
{
"left": 3
}
readFile is asynchronous, so your JSON.parse line is called before you assign a value to content, and so content has its default value of undefined.
You have two options:
Move the logic using the data into the callback.
var app = express();
var mongodb = require("mongoskin");
var fs = require('fs');
fs.readFile('./config/db.json', function read(err, data) {
if (err) {
throw err;
}
var config = JSON.parse(data); // <=== Note I'm using `data`, not `content`; we don't need a `content` variable anymore
app.get('/', function(req, res){
res.send(config.left);
});
app.listen(process.env.VCAP_APP_PORT || 3000);
});
Use the synchronous version of readFile (which is readFileSync).
// ...
content = fs.readFileSync('./config/db.json');
var config = JSON.parse(content);
// ...
content is equal to undefined when you try to parse it.
You should parse your JSON data in the readFile callback or use readFileSync instead.
Also you should probably not throw from a callback.
This leads me to think that you have some misconceptions of how node.js works and I strongly recommend you read this
Related
Having a weird issue with express vhost inside AWS. Every time I deploy I get an error in my EB log saying:
TypeError: argument hostname is required
at vhost (/var/app/current/node_modules/vhost/index.js:39:11)
at Object.<anonymous> (/var/app/current/app.js:554:9)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47
/var/app/current/node_modules/vhost/index.js:39
throw new TypeError('argument hostname is required')
^
If I have a look at the vhost module, index.js: line 36 we have the following:
function vhost(hostname, handle) {
if (!hostname) {
throw new TypeError('argument hostname is required')
}
if (!handle) {
throw new TypeError('argument handle is required')
}
if (typeof handle !== 'function') {
throw new TypeError('argument handle must be a function')
}
Not even any typechecking or anything on hostname like there is for handle, just checking if the value is passed in. Which it clearly is in the following code:
const app = express();
const register_app = express();
const nonadmin_app = express();
register_app.use(express.static(path.resolve(__dirname, './build/register')));
nonadmin_app.use(express.static(path.resolve(__dirname, './build/nonadmin')));
app.use(vhost('register.<eb-dev-url>.elasticbeanstalk.com/', register_app))
app.use(vhost('nonadmin.<eb-dev-url>.elasticbeanstalk.com/', nonadmin_app))
app.use(vhost('api.<eb-dev-url>.elasticbeanstalk.com/', api))
register_app.get('/register', (req, res) => {
res.sendFile(path.resolve(__dirname, './build/register', 'index.html'));
})
nonadmin_app.get('/nonadmin', (req, res) => {
res.sendFile(path.resolve(__dirname, './build/nonadmin', 'index.html'));
})
I'm not convinced this is a problem with vhost because when using register.localhost, nonadmin.localhost, or api.localhost when running this app locally using nodemon it works just fine. I also tried deploying with a .localhost suffix and still did not work.
Is there something I am missing in terms of AWS hostname config?
The answer was trailing slashes in the hostname argument.
Will raise a bug request.
let static_times_generate = async (static_file_path) => {
//Import MySQL database pool connection:
const db = require('../database_pool.js');
const Promise_pool = db.promise();
//Import Static Text file dependencies:
const { readFile } = require('fs/promises') , stop_times = static_file_path+'/stop_times.txt', trips = static_file_path+'/trips.txt';
let trip_data = (await readFile(trips,'utf8')).split('\n').slice(1,2);
let stop_times_data = (await readFile(stop_times,'utf8')).split('\n').slice(1,-1);
trip_data.forEach(trip_line => {
const t_array = trip_line.split(',');
stop_times_data.forEach(st_line =>{
const st_array = st_line.split(',');
if(st_array[0] == t_array[2]){
if(t_array[1] == 'SundaySum'){ t_array[1] = 'Sunday' }
else if(t_array[1] == 'SaturdaySum'){ t_array[1] = 'Saturday' }
//Here is the issue
await Promise_pool.execute(`INSERT INTO static_times (1, 2, 3, 4, 5, 6, 7) VALUES (?,?,?,?,?,?,?)`
,[elm1,elm2,elm3,elm4,elm5,elm6,elm7] )
}
});
});
console.log("COMPLETED!")
}
static_times_generate('./mysql_table_generators/STATIC_FILES'); //This is how i'm calling the function
I read files and push certain data into a MySQL database, I'm using node mysql2 for this.
let trip_data = (await readFile(trips,'utf8')).split('\n').slice(1,2);
let stop_times_data = (await readFile(stop_times,'utf8')).split('\n').slice(1,-1);
The readFile promises are being awaited just fine, but when it comes to the Promise_pool query, it's giving the error:
await Promise_pool.execute(`INSERT INTO static_times (routeId, serviceId, tripId, stopId, arrivalTime, orientation, tripHeadsign) VALUES (?,?,?,?,?,?,?)`
^^^^^
SyntaxError: await is only valid in async function
at wrapSafe (internal/modules/cjs/loader.js:979:16)
at Module._compile (internal/modules/cjs/loader.js:1027:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
I've done this kind of await in other files of my code, and it worked, Why isn't it recognizing that the await is wrapped in an async function? (I've also tried the await db.execute method, without using the db.promise() prototype)
This is my database_pool.js file
const mysql = require('mysql2');
const db_pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'drt_sms_db',
multipleStatements: true
});
module.exports = db_pool;
*** Yes I know I don't need the await, however i'm inserting 1 million rows into my database, so I get a MySQL ETIMEOUT error. await is my only option at this point.
The scope of your await call is restricted to the forEach callback function. If you want to use await you can add async to the forEach callback like this:
stop_times_data.forEach(async (st_line) => {
await doSomething();
}
That being said, the callback function here does not actually wait for the promise to finish since forEach accepts only synchronous functions. Have a look here for more details. If you need to wait for one request to finish before sending another one you should use a for loop instead.
I have created an Azure time trigger function and i want to read a Json file with him. I did install read-json and jsonfile packages and tried with both, but it did not work. Here is an example function
module.exports = function (context, myTimer) {
var timeStamp = new Date().toISOString();
var readJSON = require("read-json");
readJSON('./publishDate.json', function(error, manifest){
context.log(manifest.published);
});
context.log('Node.js timer trigger function ran!', timeStamp);
context.done();
};
Here is de error:
TypeError: Cannot read property 'published' of undefined
at D:\home\site\wwwroot\TimerTriggerJS1\index.js:8:29
at ReadFileContext.callback (D:\home\node_modules\read-json\index.js:14:22)
at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:365:13).
Json file is in same folder with the index.js. I assume that this error occurs because of the path './publishDate.json', if so how should i type a valid path?
Here's a working example that uses the built in fs module:
var fs = require('fs');
module.exports = function (context, input) {
var path = __dirname + '//test.json';
fs.readFile(path, 'utf8', function (err, data) {
if (err) {
context.log.error(err);
context.done(err);
}
var result = JSON.parse(data);
context.log(result.name);
context.done();
});
}
Note the use of __dirname to get the current working directory.
There is a quicker way than #mathewc's. NodeJS allows you to require json files directly without the explicit read -> parse steps nor without an async callback. So:
var result = require(__dirname + '//test.json');
According to this github issue the usage of __dirname wont work now, so updating the code from #mathewc with the update usage as per the wiki referred in the same issue.
replace __dirname with context.executionContext.functionDirectory
var fs = require('fs');
module.exports = function (context, input) {
var path = context.executionContext.functionDirectory + '//test.json';
fs.readFile(path, 'utf8', function (err, data) {
if (err) {
context.log.error(err);
context.done(err);
}
var result = JSON.parse(data);
context.log(result.name);
context.done();
});
}
I am developing an application with front end as angular and back end is node js, listing some values from database and send to node js .It shows some error like circular structure is there any way to override or any other option to response send back to my client side.
Node js server instance is :
app.post('/countrylist', function(req, res) {
var urlMataData = {
request : req,
responce:res
};
amqHandler.sendToAMQPServer(serialize.serialize(urlMataData),amqpConnection, 'countrylist' ,function(err,result){
console.log("callback value==>" + result)
});
amqHandler.reciveData(amqpConnection,'countrylist' ,function(err,data){
if(!err ){
console.log("am reciving request")
httpRequestHandler. makeHttpRequest(data,'countrylist', function(row){
console.log("CountryType==>"+ JSON.parse( row));
//res.json(row);
});
} else {
res.json(err);
}
});
});
Request handler is :
var countryList = function(req, res, next) {
query = 'SELECT id_country, country FROM edu.tbl_country';
database.getConnection(function (err, con) {
if(!err){
con.query(query, function(err,row) {
console.log("row type:"+ typeof row );
//res.contentType('application/json');
res.json(JSON.stringify(row));
});
}
});
};
Error
var body = JSON.stringify(val, replacer, spaces);
^
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at ServerResponse.json (/root/nodejsworkspace/EDU/rabitmq/node_modules/express/lib/response.js:228:19)
at ClientRequest.<anonymous> (/root/nodejsworkspace/EDU/rabitmq/AMQPServer.js:116:23)
at ClientRequest.g (events.js:273:16)
at emitOne (events.js:90:13)
at ClientRequest.emit (events.js:182:7)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:469:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:103:23)
at Socket.socketOnData (_http_client.js:359:20)
at emitOne (events.js:90:13)
I am a node.js beginner and I am trying to read a json file, but when I'm running 'npm start' in the terminal I get this error:
undefined:3462
SyntaxError: Unexpected end of input
at Object.parse (native)
at /Users/alonbond/node_apps/analoc_2/analoc/routes/index.js:15:20
at fs.js:334:14
at FSReqWrap.oncomplete (fs.js:95:15)
this is index.js:
var express = require('express');
var fs = require('fs');
var app = express.Router();
/* GET home page. */
app.get('/', function(req, res, next) {
console.log('Welcome to Express.js');
res.render('index', { title: 'Express' });
});
/* GET json */
app.get('/analoc/', function(req, res) {
fs.readFile('./sample_data.json', function(error, data){
jsonObj = JSON.parse(data);
res.send('THE DATA: ', jsonObj);
});
});
module.exports = app;
Any help?
thanks!
readFile is the asynchronous version. You should either just use readFileSync, or rewrite it to be properly asynchronous.
console.log('analoc request');
var fs = require('fs');
fs.readFile('./files/sample_data.json', function(err,config){
console.log('Config: ' + JSON.parse(config));
});
Or:
var config = fs.readFileSync('./files/sample_data.json');
console.log('Config: ' + JSON.parse(config));
readFile doesn't have a return value. You are trying to parse "undefined" as if it were JSON. The file is passed to the callback function after it has been read.
fs.readFile('./files/sample_data.json', function (err, data) {
if (err) throw err;
var config = JSON.parse(data);
console.log('Config: ', config);
});