Pobierz dane z fs.readFile
var content;
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
console.log(content);
Logi undefined
, Dlaczego?
13 answers
Aby rozwinąć to, co powiedział @Raynos, zdefiniowana funkcja jest asynchronicznym wywołaniem zwrotnym. Nie wykonuje się go od razu, a raczej wykonuje po zakończeniu ładowania pliku. Po wywołaniu readFile, kontrola jest zwracana natychmiast i następny wiersz kodu jest wykonywany. Więc kiedy zadzwonisz do konsoli.log, Twoja odpowiedź zwrotna nie została jeszcze wywołana, a ta zawartość nie została jeszcze ustawiona. Witamy w programowaniu asynchronicznym.
Przykładowe podejścia
const fs = require('fs');
var content;
// First I want to read the file
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
// Invoke the next step here however you like
console.log(content); // Put all of the code here (not the best solution)
processFile(); // Or put the next step in a function and invoke it
});
function processFile() {
console.log(content);
}
Albo jeszcze lepiej, jako Przykład Raynos pokazuje, zawiń połączenie w funkcję i przekaż własne wywołania zwrotne. (Najwyraźniej jest to lepsza praktyka) myślę, że wchodzenie w nawyk owijania połączeń asynchronicznych w funkcji, która trwa oddzwanianie, zaoszczędzi Ci wiele kłopotów i niechlujnego kodu.
function doSomething (callback) {
// any async callback invokes callback with response
}
doSomething (function doSomethingAfter(err, result) {
// process the async result
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-26 11:00:34
Istnieje funkcja Synchroniczna dla tego:
Http://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_encoding
asynchroniczne
fs.readFile(filename, [encoding], [callback])
asynchronicznie odczytuje całą zawartość pliku. Przykład:
fs.readFile('/etc/passwd', function (err, data) {
if (err) throw err;
console.log(data);
});
wywołanie zwrotne jest przekazywane dwoma argumentami (err, data), gdzie dane są zawartością pliku.
jeżeli nie podano kodowania, wtedy bufor surowy jest zwrócony.
Synchroniczne
fs.readFileSync(filename, [encoding])
Synchroniczna wersja fs.readFile. Zwraca zawartość pliku o nazwie filename.
jeżeli kodowanie jest określone, to funkcja zwraca łańcuch znaków. W przeciwnym razie zwraca bufor.
var text = fs.readFileSync('test.md','utf8')
console.log (text)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-17 00:22:37
function readContent(callback) {
fs.readFile("./Index.html", function (err, content) {
if (err) return callback(err)
callback(null, content)
})
}
readContent(function (err, content) {
console.log(content)
})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-22 23:38:17
Używanie obietnic z ES7
Użycie asynchroniczne z mz / fs
The mz
moduł udostępnia promisyfikowane wersje biblioteki węzłów core. Korzystanie z nich jest proste. Najpierw zainstaluj bibliotekę...
npm install mz
Wtedy...
const fs = require('mz/fs');
fs.readFile('./Index.html').then(contents => console.log(contents))
.catch(err => console.error(err));
Alternatywnie można je zapisać w funkcjach asynchronicznych:
async function myReadfile () {
try {
const file = await fs.readFile('./Index.html');
}
catch (err) { console.error( err ) }
};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-20 14:00:48
var data = fs.readFileSync('tmp/reltioconfig.json','utf8');
Użyj tego do wywołania pliku synchronicznie, bez kodowania jego wyjścia jako bufora.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-24 08:20:42
Synchronizacja i asynchroniczny odczyt plików:
//fs module to read file in sync and async way
var fs = require('fs'),
filePath = './sample_files/sample_css.css';
// this for async way
/*fs.readFile(filePath, 'utf8', function (err, data) {
if (err) throw err;
console.log(data);
});*/
//this is sync way
var css = fs.readFileSync(filePath, 'utf8');
console.log(css);
Node Cheat dostępny pod adresem read_file .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-16 07:50:33
Jak już wspomniano, fs.readFile
jest akcją asynchroniczną. Oznacza to, że kiedy każesz node odczytać plik, musisz wziąć pod uwagę, że zajmie to trochę czasu, a w międzyczasie node kontynuował uruchamianie następującego kodu. W Twoim przypadku to: console.log(content);
.
To jak wysłanie części kodu na długą podróż (jak czytanie dużego pliku).
Spójrz na komentarze, które napisałem:
var content;
// node, go fetch this file. when you come back, please run this "read" callback function
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
// in the meantime, please continue and run this console.log
console.log(content);
Dlatego {[3] } jest nadal pusty po zalogowaniu. node nie odzyskał jeszcze pliku treść.
Można to rozwiązać przenosząc console.log(content)
wewnątrz funkcji zwrotnej, zaraz po content = data;
. W ten sposób zobaczysz dziennik, gdy node skończy czytać plik i po content
otrzyma wartość.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-07 23:33:14
var fs = require('fs');
var path = (process.cwd()+"\\text.txt");
fs.readFile(path , function(err,data)
{
if(err)
console.log(err)
else
console.log(data.toString());
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-24 11:22:34
const fs = require('fs')
function readDemo1(file1) {
return new Promise(function (resolve, reject) {
fs.readFile(file1, 'utf8', function (err, dataDemo1) {
if (err)
reject(err);
else
resolve(dataDemo1);
});
});
}
async function copyFile() {
try {
let dataDemo1 = await readDemo1('url')
dataDemo1 += '\n' + await readDemo1('url')
await writeDemo2(dataDemo1)
console.log(dataDemo1)
} catch (error) {
console.error(error);
}
}
copyFile();
function writeDemo2(dataDemo1) {
return new Promise(function(resolve, reject) {
fs.writeFile('text.txt', dataDemo1, 'utf8', function(err) {
if (err)
reject(err);
else
resolve("Promise Success!");
});
});
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-23 21:25:42
Możesz odczytać plik przez
var readMyFile = function(path, cb) {
fs.readFile(path, 'utf8', function(err, content) {
if (err) return cb(err, null);
cb(null, content);
});
};
Dodawanie można zapisać do pliku,
var createMyFile = (path, data, cb) => {
fs.writeFile(path, data, function(err) {
if (err) return console.error(err);
cb();
});
};
I nawet połączyć je razem
var readFileAndConvertToSentence = function(path, callback) {
readMyFile(path, function(err, content) {
if (err) {
callback(err, null);
} else {
var sentence = content.split('\n').join(' ');
callback(null, sentence);
}
});
};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-17 13:35:06
var content;
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
console.log(content);
Dzieje się tak tylko dlatego, że node jest asynchroniczny i nie będzie czekał na funkcję read i jak tylko program się uruchomi, będzie konsolować wartość jako undefined, co jest w rzeczywistości prawdą, ponieważ nie ma wartości przypisanej do zmiennej content. Do obsługi możemy użyć obietnic, generatorów itp. W ten sposób możemy użyć obietnicy.
new Promise((resolve,reject)=>{
fs.readFile('./index.html','utf-8',(err, data)=>{
if (err) {
reject(err); // in the case of error, control flow goes to the catch block with the error occured.
}
else{
resolve(data); // in the case of success, control flow goes to the then block with the content of the file.
}
});
})
.then((data)=>{
console.log(data); // use your content of the file here (in this then).
})
.catch((err)=>{
throw err; // handle error here.
})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-02 09:49:48
Mówiąc mniej więcej, masz do czynienia z węzłem.js, który ma charakter asynchroniczny.
Kiedy mówimy o asynchronizacji, mówimy o robieniu lub przetwarzaniu informacji lub danych podczas radzenia sobie z czymś innym. Nie jest synonimem parallel, proszę pamiętać.
Twój kod:
var content;
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
});
console.log(content);
Z Twoją próbką, to w zasadzie robi konsolę.najpierw zaloguj część, w ten sposób zmienna' content ' jest niezdefiniowana.
Jeśli naprawdę chcesz wyjść, zrób coś takiego zamiast:
var content;
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
console.log(content);
});
To jest asynchroniczne. Trudno będzie się do tego przyzwyczaić, ale jest jak jest.
Ponownie, jest to przybliżone, ale szybkie wyjaśnienie, czym jest async.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-17 07:51:22
Użyj wbudowanej biblioteki promisify, aby uczynić te stare funkcje zwrotne bardziej eleganckimi.
const fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);
async function doStuff() {
try {
const content = await readFile(filePath, 'utf8');
console.log(content);
} catch (e) {
console.error(e);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-19 18:37:15