A
A
Alexander Degtyarev2018-03-04 15:47:09
Node.js
Alexander Degtyarev, 2018-03-04 15:47:09

Why is there no data assignment in nodejs?

var express = require('express');
var fs = require('fs');
var app = express();

app.get('/', function (req, res) {
    let json = {};

    fs.readFile('user.json', function (err, data) {
        json += data.toString();
    });

    res.json(json);
});

app.listen(8000, function () {
    console.log('Server Run!');
});

Why is the data from the stream not assigned and how to make it assigned? Through streams?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-03-04
@alexdeg

The readFile method is asynchronous. Instead of

let json = {};

fs.readFile('user.json', function (err, data) {
    json += data.toString();
});

res.json(json);

do like this:
fs.readFile('user.json', function (err, data) {
  res.json(data.toString());
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question