我对在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,打开'./start.html']错误:34,代码:'ENOENT',路径:'。/ start.html'}
有什么想法吗?
答案 0 :(得分:169)
使用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。
答案 1 :(得分:31)
使用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()会返回一个Buffer或字符串。
fs
正确地假设相对路径是安全问题。 path
是一种解决方法。
要以字符串形式加载,请指定编码:
return fs.readFileSync(path,{ encoding: 'utf8' });
答案 2 :(得分:16)
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());
答案 3 :(得分:4)
使用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>
答案 4 :(得分:3)
运行此代码,它将从文件中获取数据并在控制台中显示
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 :(得分:2)
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 :(得分:2)
如果您想知道如何在目录中读取文件并使用该文件执行某些操作,请继续。这也显示了如何通过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 :(得分:0)
与节点的简单同步方式:
let fs = require('fs')
let filename = "your-file.something"
let content = fs.readFileSync(process.cwd() + "/" + filename).toString()
console.log(content)
答案 8 :(得分:0)
简单易用:
const Store = require('data-store');
const store = new Store({ path: 'filepath/file.json' });
阅读:
store.get('keyname');
用于更新:
store.set('keyname',value);