在 Node.js 中读取文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18386361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read a file in Node.js
提问by Eugene Kostrikov
I'm quite puzzled with reading files in 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);
}
});
File start.htmlis in the same directory with file that tries to open and read it.
文件start.html与试图打开和读取它的文件位于同一目录中。
However, in the console I get:
但是,在控制台中我得到:
{ [Error: ENOENT, open './start.html'] errno: 34, code: 'ENOENT', path: './start.html' }
{ [错误:ENOENT,打开 './start.html'] 错误号:34,代码:'ENOENT',路径:'./start.html' }
Any ideas?
有任何想法吗?
回答by Eugene Kostrikov
Use path.join(__dirname, '/start.html');
使用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);
}
});
Thanks to dc5.
感谢 dc5。
回答by Michael Cole
With Node 0.12, it's possible to do this synchronously now:
使用 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....
}
fsis the file system. readFileSync()returns a Buffer, or string if you ask.
fs是文件系统。 readFileSync()返回一个缓冲区,如果你问,或者字符串。
fscorrectly assumes relative paths are a security issue. pathis a work-around.
fs正确假设相对路径是一个安全问题。 path是一种变通方法。
To load as a string, specify the encoding:
要加载为字符串,请指定编码:
return fs.readFileSync(path,{ encoding: 'utf8' });
回答by Masoud Siahkali
1).For ASync :
1).对于异步:
var fs = require('fs');
fs.readFile(process.cwd()+"\text.txt", function(err,data)
{
if(err)
console.log(err)
else
console.log(data.toString());
});
2).For Sync :
2).对于同步:
var fs = require('fs');
var path = process.cwd();
var buffer = fs.readFileSync(path + "\text.txt");
console.log(buffer.toString());
回答by localhostdotdev
simple synchronous way with node:
与节点的简单同步方式:
let fs = require('fs')
let filename = "your-file.something"
let content = fs.readFileSync(process.cwd() + "/" + filename).toString()
console.log(content)
回答by Gajender Singh
Run this code, it will fetch data from file and display in console
运行此代码,它将从文件中获取数据并显示在控制台中
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());
回答by Aaditya
To read the html file from server using httpmodule. This is one way to read file from server. If you want to get it on console just remove httpmodule declaration.
使用http模块从服务器读取 html 文件。这是从服务器读取文件的一种方法。如果您想在控制台上获取它,只需删除http模块声明。
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res) {
fs.readFile('HTMLPage1.html', function(err, data) {
if (!err) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.write(data);
res.end();
} else {
console.log('error');
}
});
});
server.listen(8000, function(req, res) {
console.log('server listening to localhost 8000');
});
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
回答by SovietFrontier
If you want to know how to read a file, within a directory, and do something with it, here you go. This also shows you how to run a command through the power shell. This is in TypeScript! I had trouble with this, so I hope this helps someone one day. Feel free to down vote me if you think its THAT unhelpful. What this did for me was webpackall of my .tsfiles in each of my directories within a certain folder to get ready for deployment. Hope you can put it to use!
如果您想知道如何在目录中读取文件并对其进行处理,那么您就可以了。这也向您展示了如何通过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);
回答by Nikunj K.
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);
}
});

