Прочтите файл в Node.js
Я очень озадачен чтением файлов в Node.js.
fs.open('./start.html', 'r', function(err, fileToRead){
if (!err){
fs.readFile(fileToRead, {encoding: 'utf-8'}, function(err,data){
if (!err){
console.log('received data: ' + data);
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
}else{
console.log(err);
}
});
}else{
console.log(err);
}
});
Файл start.html
находится в том же каталоге с файлом, который пытается открыть и прочитать его.
Однако в консоли я получаю:
{[Ошибка: ENOENT, open './start.html'] errno: 34, code: 'ENOENT', путь: './start.html'}
Любые идеи?
Ответы
Ответ 1
Использовать path.join(__dirname, '/start.html')
;
var fs = require('fs'),
path = require('path'),
filePath = path.join(__dirname, 'start.html');
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
if (!err) {
console.log('received data: ' + data);
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
} else {
console.log(err);
}
});
Благодаря dc5.
Ответ 2
С Node 0.12 теперь можно сделать это синхронно:
var fs = require('fs');
var path = require('path');
// Buffer mydata
var BUFFER = bufferFile('../public/mydata.png');
function bufferFile(relPath) {
return fs.readFileSync(path.join(__dirname, relPath)); // zzzz....
}
fs
- это файловая система. readFileSync() возвращает буфер или строку, если вы спросите.
fs
правильно предполагает, что относительные пути являются проблемой безопасности. path
- это обход.
Чтобы загрузить в качестве строки, укажите кодировку:
return fs.readFileSync(path,{ encoding: 'utf8' });
Ответ 3
1). Для ASync:
var fs = require('fs');
fs.readFile(process.cwd()+"\\text.txt", function(err,data)
{
if(err)
console.log(err)
else
console.log(data.toString());
});
2). Для синхронизации:
var fs = require('fs');
var path = process.cwd();
var buffer = fs.readFileSync(path + "\\text.txt");
console.log(buffer.toString());
Ответ 4
Запустите этот код, он будет извлекать данные из файла и отображать на консоли
function fileread(filename){
var contents= fs.readFileSync(filename);
return contents;
}
var fs =require("fs"); // file system
var data= fileread("abc.txt");
//module.exports.say =say;
//data.say();
console.log(data.toString());
Ответ 5
var fs = require('fs');
var path = require('path');
exports.testDir = path.dirname(__filename);
exports.fixturesDir = path.join(exports.testDir, 'fixtures');
exports.libDir = path.join(exports.testDir, '../lib');
exports.tmpDir = path.join(exports.testDir, 'tmp');
exports.PORT = +process.env.NODE_COMMON_PORT || 12346;
// Read File
fs.readFile(exports.tmpDir+'/start.html', 'utf-8', function(err, content) {
if (err) {
got_error = true;
} else {
console.log('cat returned some content: ' + content);
console.log('this shouldn\'t happen as the file doesn\'t exist...');
//assert.equal(true, false);
}
});
Ответ 6
Если вы хотите знать, как читать файл в каталоге и что-то с ним делать, то вы идете. Здесь также показано, как запустить команду через power shell
. Это в TypeScript
! У меня были проблемы с этим, поэтому я надеюсь, что это поможет кому-то однажды. Не стесняйтесь голосовать против меня, если вы считаете, что это бесполезно. Это сделало для меня webpack
всех моих файлов .ts
в каждом из моих каталогов в определенной папке, чтобы подготовиться к развертыванию. Надеюсь, вы можете использовать его!
import * as fs from 'fs';
let path = require('path');
let pathDir = '/path/to/myFolder';
const execSync = require('child_process').execSync;
let readInsideSrc = (error: any, files: any, fromPath: any) => {
if (error) {
console.error('Could not list the directory.', error);
process.exit(1);
}
files.forEach((file: any, index: any) => {
if (file.endsWith('.ts')) {
//set the path and read the webpack.config.js file as text, replace path
let config = fs.readFileSync('myFile.js', 'utf8');
let fileName = file.replace('.ts', '');
let replacedConfig = config.replace(/__placeholder/g, fileName);
//write the changes to the file
fs.writeFileSync('myFile.js', replacedConfig);
//run the commands wanted
const output = execSync('npm run scriptName', { encoding: 'utf-8' });
console.log('OUTPUT:\n', output);
//rewrite the original file back
fs.writeFileSync('myFile.js', config);
}
});
};
// loop through all files in 'path'
let passToTest = (error: any, files: any) => {
if (error) {
console.error('Could not list the directory.', error);
process.exit(1);
}
files.forEach(function (file: any, index: any) {
let fromPath = path.join(pathDir, file);
fs.stat(fromPath, function (error2: any, stat: any) {
if (error2) {
console.error('Error stating file.', error2);
return;
}
if (stat.isDirectory()) {
fs.readdir(fromPath, (error3: any, files1: any) => {
readInsideSrc(error3, files1, fromPath);
});
} else if (stat.isFile()) {
//do nothing yet
}
});
});
};
//run the bootstrap
fs.readdir(pathDir, passToTest);
Ответ 7
простой синхронный способ с узлом:
let fs = require('fs')
let filename = "your-file.something"
let content = fs.readFileSync(process.cwd() + "/" + filename).toString()
console.log(content)
Ответ 8
Простое использование:
const Store = require('data-store');
const store = new Store({ path: 'filepath/file.json' });
для чтения:
store.get('keyname');
для обновления:
store.set('keyname',value);